首页 > 解决方案 > 在python中将输入作为字典读取

问题描述

我试图以字典的形式读取跨多行的输入,并对字典的值应用简单的数学运算。我的代码读取

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

ISSUE:这里的问题是代码总是只读取 2 和最后一个值。例如在上面的例子中输出是 {'D': 600, 'W': 200} 400

有人可以让我知道 for loop 的问题吗?提前致谢

标签: python-3.x

解决方案


您可以使用自己的方法以更简单的方式进行尝试。@Rakesh@Sabesh建议好。Dictionary 是一个具有唯一且不可变键的无序集合。您可以通过执行在 Python 交互式控制台上轻松检查这一点help(dict)

您可以查看https://docs.python.org/2/library/collections.html#collections.defaultdict。在这里,您将找到许多有关如何有效使用字典的示例。

>>> d = {}
>>> text = 'W 300,W 200,D 100,D 400,D 600'
>>>
>>> for item in text.split(","):
...     arr = item.split()
...     d.setdefault(arr[0], []).append(arr[1])
...
>>> d
{'W': ['300', '200'], 'D': ['100', '400', '600']}
>>>
>>> w = [int(n) for n in d['W']]
>>> d = [int(n) for n in d['D']]
>>>
>>> bal = sum(d) - sum(w)
>>> bal
600
>>>

推荐阅读