python-3.x - 在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 的问题吗?提前致谢
解决方案
您可以使用自己的方法以更简单的方式进行尝试。@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
>>>
推荐阅读
- angular - 如何使用会话存储以角度区分窗口关闭和窗口刷新
- javascript - 功能无线电组件未按预期显示
- android - gradle 更新后,Google 服务插件为客户端搜索错误的 google-services.json 文件
- html - Angular Dom Sanitizer HTML 无法复制文本
- generics - 从 Kotlin 的映射中过滤空键和值
- mysql - How to perform integer arithmetic to a string in MySQL?
- c - 如何使用 strtok 和 sscanf 监控有效输入
- java - 如何在 Java 中保存来自 POST 请求输出的数据?
- symfony4 - 使用预设数据并更改值
- python - VSCode 发现测试错误:生成 python ENOENT