我试图读取以字典形式分布在多行上的输入,并对字典的值应用简单的数学运算。我的代码读取
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循环的问题吗? 预先感谢
答案 0 :(得分:0)
您可以使用自己的方法以更简单的方式进行尝试。 { "text": "who is John", "entities" : [ { "type": "PER" "startPos" :7 "endPos" :11 } ] }
和@Rakesh
表示不错。字典是具有唯一且不变的键的无序集合。您可以通过执行@Sabesh
在Python交互式控制台上轻松地进行检查。
您可以检查https://docs.python.org/2/library/collections.html#collections.defaultdict。在这里,您将找到许多有关如何有效使用字典的示例。
help(dict)