我试图让用户输入单独添加到每个列表,而不覆盖其他输入。但是,当另一个用户输入输入时,它将覆盖它。我该如何解决。
runner1stats = []
runner2stats = []
runner3stats = []
runner1 = input("What is the name of the first runner in your team?")
runner2 = input("What is the name of the second runner in your team?")
runner3 = input("What is the name of the third runner in your team?")
runners = [runner1,runner2,runner3]
for i in runners:
race1 = int(input("Enter rider placing for race 1:"))
race2 = int(input("Enter rider placing for race 2:"))
race3 = int(input("Enter rider placing for race 3:"))
race4 = int(input("Enter rider placing for race 4:"))
runner1stats.append({
"RacerName": runner1,
"Race1Points": race1,
"Race2Points": race2,
"Race3Points": race3,
"Race4Points": race4,
})
runner2stats.append ({
"RacerName": runner2,
"Race1Points": race1,
"Race2Points": race2,
"Race3Points": race3,
"Race4Points": race4,
})
runner3stats.append ({
"RacerName": runner3,
"Race1Points": race1,
"Race2Points": race2,
"Race3Points": race3,
"Race4Points": race4,
})
答案 0 :(得分:0)
您可能正在寻找类似的东西。
runner1 = input("What is the name of the first runner in your team?")
runner2 = input("What is the name of the second runner in your team?")
runner3 = input("What is the name of the third runner in your team?")
runner_stats = [] # This will end up having 3 entries by the end of the loop.
for name in [runner1, runner2, runner3]:
race1 = int(input(name + ": Enter rider placing for race 1:"))
race2 = int(input(name + ": Enter rider placing for race 2:"))
race3 = int(input(name + ": Enter rider placing for race 3:"))
race4 = int(input(name + ": Enter rider placing for race 4:"))
runner_stats.append({
"RacerName": name,
"Race1Points": race1,
"Race2Points": race2,
"Race3Points": race3,
"Race4Points": race4,
})
print(runner_stats)
答案 1 :(得分:0)
for i in runners:
race1 = int(input("Enter rider placing for race 1:"))
race2 = int(input("Enter rider placing for race 2:"))
race3 = int(input("Enter rider placing for race 3:"))
race4 = int(input("Enter rider placing for race 4:"))
表示“对于每个跑步者,将race1-4变量设置为输入值”-因此每个新迭代都会覆盖上一个迭代。
您不应该在变量名中使用硬编码索引,这是一种更简单,更安全的方法:
runnerstats = {}
runners = []
for i, pos in enumerate(("first", "second", "third")):
runners.append(input("What is the name of the {} runner in your team?").format(pos))
for runner in runners:
races = []
for i in range(4)
races.append(int(input("Enter rider placing for race {}:".format(i+1))))
runnerstats[runner] = races