Python中如何分割单行输入并按问题编号分行输出结果
解决分行显示Q1-Q10答案的问题
我来帮你搞定这个问题!你当前的代码只是拆分了输入的答案串,但没有把每个答案和对应的问题编号关联起来输出。这里有两种实用的改进方案,推荐用更简洁的循环写法,也可以保留你原来的变量定义方式:
推荐方案:用循环批量处理(简洁易维护)
这种方式不需要硬编码每个Q1-Q10的变量,还能处理用户输入答案数量不足的情况,避免报错:
input_str = "What are your answers for Q1 to Q10? (leave a space between each answer) " # 使用默认split()按任意空白分割(兼容多空格输入) answers = input(input_str).split() # 遍历Q1到Q10,逐个输出对应答案 for question_num in range(1, 11): # 计算答案的索引(列表从0开始,所以要减1) answer_index = question_num - 1 if answer_index < len(answers): print(f"Q{question_num} {answers[answer_index]}") else: print(f"Q{question_num} 未提供答案")
备选方案:保留原变量定义后逐个输出
如果你更习惯用单独的变量存储每个答案,可以这样修改,同时加入边界检查避免索引错误:
input_str = "What are your answers for Q1 to Q10? (leave a space between each answer) " qns = input(input_str) questions = qns.split() # 定义每个问题的答案,加入长度检查防止报错 Q1 = questions[0] if len(questions) >= 1 else "未提供" Q2 = questions[1] if len(questions) >= 2 else "未提供" Q3 = questions[2] if len(questions) >= 3 else "未提供" Q4 = questions[3] if len(questions) >= 4 else "未提供" Q5 = questions[4] if len(questions) >= 5 else "未提供" Q6 = questions[5] if len(questions) >= 6 else "未提供" Q7 = questions[6] if len(questions) >= 7 else "未提供" Q8 = questions[7] if len(questions) >= 8 else "未提供" Q9 = questions[8] if len(questions) >= 9 else "未提供" Q10 = questions[9] if len(questions) >= 10 else "未提供" # 每行输出一个问题和答案 print(f"Q1 {Q1}") print(f"Q2 {Q2}") print(f"Q3 {Q3}") print(f"Q4 {Q4}") print(f"Q5 {Q5}") print(f"Q6 {Q6}") print(f"Q7 {Q7}") print(f"Q8 {Q8}") print(f"Q9 {Q9}") print(f"Q10 {Q10}")
测试效果
比如用户输入示例:a b c d e a b c d(9个答案),输出会是:
Q1 a
Q2 b
Q3 c
Q4 d
Q5 e
Q6 a
Q7 b
Q8 c
Q9 d
Q10 未提供答案
内容的提问来源于stack exchange,提问作者chloe ong
相关产品推荐
相关产品推荐

