【问题标题】:Reading input as dictionary in python在python中将输入作为字典读取
【发布时间】: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


【解决方案1】:

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

您可以查看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
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 2018-03-19
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多