[英]How to do a string plus string operation in Dictionary condition in python?
My function is like 我的功能就像
def calResult(w,t,l,team):
wDict={}
for item in team:
for x in w:
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
for x in t:
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
return wDict
say I create the empty dict then I use wDict[item]
to assign value for each key(these are from a team list, we have team like abc d...). 说我创建一个空字典,然后使用
wDict[item]
为每个键分配值(这些是从团队列表中获得的,我们有像abc d这样的团队...)。 the x[item.index(" "):item.index(" ")+1]
part will return a value after the int method have run. 运行int方法后,
x[item.index(" "):item.index(" ")+1]
部分将返回一个值。 But the python shell returned that 但是python shell返回了
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 66, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 59, in calResult
builtins.KeyError: 'Torino'
I can't understand what exactly is the error in my code. 我无法理解代码中的错误到底是什么。
I'm not quite sure what you're trying to do here (consider using more descriptive variable names than x
, for starters), but here is the problem: 我不太确定您要在这里做什么(对于初学者,请考虑使用比
x
更具描述性的变量名),但这是问题所在:
wDict[item]=int(wDict[item])+...
The first time you do this, wDict[item]
doesn't exist, hence the KeyError
. 第一次执行此操作时,
wDict[item]
不存在,因此出现KeyError
。
What you want, I think, is: 我想您想要的是:
wDict[item] = wDict.get(item, 0) + int(x[item.index(" "):item.index(" ")+1])
.get()
takes a key and a default value to use if that key doesn't exist. .get()
需要一个密钥和一个默认值(如果该密钥不存在)。
You might also want to use the Counter
class in collections
, which is designed to default nonexistent keys to zero for just this sort of situation. 您可能还希望在
collections
使用Counter
类,该类旨在将不存在的键默认为零。
You can not access wDict[item]
the first time, since your dict is empty 您的字典为空,因此您第一次无法访问
wDict[item]
This would be ok: 可以的:
wDict[item] = 1
But you can not do this : 但是您不能这样做:
wDict[item] = wDict[item] + 1
Maybe you want to use this syntax : 也许您想使用以下语法:
wDict[item] = int(wDict.get(item, 0)]) + int(x[item.index(" "):item.index(" ") + 1])
Looks like you are trying to use wDict[item] as the rvalue and the lvalue in the same assignment statement, when wDict[item] is not yet initialized. 似乎您正在尝试在尚未初始化wDict [item]的情况下,在同一赋值语句中将wDict [item]用作右值和左值。
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
You are trying to access the "value" of the key item, but there is no key value pair initialized. 您正在尝试访问键项目的“值”,但是没有初始化键值对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.