You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python先收集全部输入再统一输出姓名首字母?

Fix: Collect All Inputs First, Then Output Initials Together

Got it, let's sort this out! The issue with your current code is that it prints each initial as soon as you enter a name—instead of storing all those initials first and then displaying them all at once.

What's Wrong with the Current Code?

Your loop prints each initial immediately after splitting the name, which is why you see output right after every input. We need to hold onto those initials until all names are entered.

Updated Code That Meets Your Needs

num_of_people = int(input("How many people will attend the meeting? "))
# Create an empty list to store all initials
initials = []

for i in range(num_of_people):
    name = input(f"What is the full name of participant {i+1}? ")
    split_name = name.split(" ")
    # Calculate initials for this name and add to the list
    name_initials = [word[0] for word in split_name]
    # Join initials into a single string (e.g., "J D" for "John Doe") and add to the main list
    initials.append(' '.join(name_initials))

# Now print all initials together
print("\nAll participant initials:")
for idx, initial in enumerate(initials, 1):
    print(f"Participant {idx}: {initial}")

Breakdown of the Changes:

  • Added an empty list initials: This acts as a storage container for all the initial sets we'll generate.
  • List comprehension for initials: Instead of looping through each word to print, we use [word[0] for word in split_name] to generate all initials for a single name at once.
  • Store initials instead of printing: We join the individual initials into a readable string (like "J S" for "Jane Smith") and add it to our initials list.
  • Print after all inputs: Once all names are entered, we loop through the initials list and print everything out in one go.

If you prefer a more compact output (like all initials in one line), you could replace the final loop with:

print("\nAll participant initials:", ", ".join(initials))

内容的提问来源于stack exchange,提问作者new_programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:37:12