【发布时间】:2018-06-25 23:35:35
【问题描述】:
我正在处理的程序中的一个函数获取一个测验分数列表,并要求用户输入一轮名称和分数。如果轮次已经存在,则将新分数附加到现有列表中,否则将轮次及其分数添加到列表的顶层:
lines = [['geography', '8', '4', '7'],
['tv and cinema', '4', '4', '8', '7', '7'],
['all creatures great and small', '7', '8'],
['odd one out', '4', '7'],
['music', '3', '5', '8', '8', '7'],
['how many', '4']]
roundName = input("Enter the name of the round to add: ")
score = input("Enter the score for that round: ")
for line in lines:
if roundName in line:
line.append(score)
lines.append([roundName, score])
#for line in lines:
# if line[0] == roundName.lower().strip():
# existingRound = lines.index(line)
# lines[existingRound].append(score)
# else:
# newRound = [roundName, score]
# lines.append(newRound)
评论部分代表我最初的几次尝试。输入how many,3 应该会导致
lines = [['geography', '8', '4', '7'],
['tv and cinema', '4', '4', '8', '7', '7'],
['all creatures great and small', '7', '8'],
['odd one out', '4', '7'],
['music', '3', '5', '8', '8', '7'],
['how many', '4', '3']]
#actually results, in
[['geography', '8', '4', '7'],
['tv and cinema', '4', '4', '8', '7', '7'],
['all creatures great and small', '7', '8'],
['odd one out', '4', '7'],
['music', '3', '5', '8', '8', '7'],
['how many', '4', '3'],
['how many', '3']]
我无法正确理解循环中的逻辑。我哪里错了?
【问题讨论】:
-
你绝对应该为此使用字典
标签: python-3.x list nested-lists