【问题标题】:Python: Can't change a dictionary field while iterating over itPython:迭代字典字段时无法更改它
【发布时间】:2018-09-09 23:48:39
【问题描述】:

我有这个清单:

>>> stud
[19, 11, 6, 26]

如果我遍历 'draws' 字段,我会得到以下信息:

>>> [aluDict[str(s)]['draws'] for s in stud]
[1, 0, 1, 0]

现在我想将1 添加到其中的每一个,以便获得(可能)以下内容:

>>> [aluDict[str(s)]['draws'] for s in stud]
[2, 1, 2, 1]

为了做到这一点,我尝试了这个:

>>> [aluDict[str(s)]['draws']+=1 for s in stud]
  File "<stdin>", line 1
    [aluDict[str(s)]['draws']+=1 for s in stud]
                              ^
SyntaxError: invalid syntax

如果我单独做,我可以做到:

>>> aluDict[str(19)]['draws']
2
>>> aluDict[str(19)]['draws']+=1
>>> aluDict[str(19)]['draws']
3

为什么会这样?我错过了什么?

谢谢!

【问题讨论】:

  • 您不能在列表推导中进行分配(目前)。

标签: python-3.x dictionary foreach


【解决方案1】:

如果您只想要[2, 1, 2, 1] 列表并且不想实际更改存储在aluDict 中的任何值,请使用+1:

[aluDict[str(s)]['draws']+1 for s in stud]

【讨论】:

  • 显然,但我认为我们的想法是更新这些值。
猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 2016-09-29
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 2021-07-26
  • 1970-01-01
相关资源
最近更新 更多