【发布时间】:2019-01-11 06:15:24
【问题描述】:
我试图以字典的形式读取分布在多行中的输入,并对字典的值应用简单的数学运算。我的代码是
d ={}
bal=0
text = input().split(",") #split the input text based on line'text'
print(text)
for i in range(5):
text1 = text[i].split(" ") #split the input text based on space & store in the list 'text1'
d[text1[0]] = int(text1[1]) #assign the 1st item to key and 2nd item to value of the dictionary
print(d)
for key in d:
if key=='D':
bal=bal+int(d[key])
#print(d[key])
elif key=='W':
bal=bal-int(d[key])
print(bal)
输入:W 300,W 200,D 100,D 400,D 600 输出:{'D':600,'W':200} 400 预期输出:{'W':300,'W':200,'D':100,'D':400,'D':600} 600
问题:这里的问题是代码总是只读取 2 和最后一个值。例如在上述情况下输出是 {'D':600,'W':200} 400
有人可以告诉我 for loop 的问题吗? 提前致谢
【问题讨论】:
-
字典中不能有重复的键。
-
正如@Rakesh 字典所说,不能有重复的键。您将在此处覆盖现有键的值。因此,您将获得 W 和 D 的最新值
{'W': 200, 'D': 600}。您的代码没有任何问题。
标签: python-3.x