【问题标题】:How to update the list elements in a defaultdict(list) dictionary?如何更新 defaultdict(list) 字典中的列表元素?
【发布时间】:2022-01-10 22:40:46
【问题描述】:

我正在使用 Python 的集合库来制作一个字典,其中键是整数,值是列表。我正在使用defaultdict(list) 命令。我正在尝试编辑这些列表中的元素,但没有成功。

我认为列表理解应该适用于此,但我不断收到语法错误。我附上我在下面尝试过的内容:

import collections 

test = collections.defaultdict(list) 
test[4].append(1)
test[4].append(5)
test[4].append(6)
#This would yield {4: [1,5,6]}

run_lengths = [1,3,4,6] #dummy data

for i in run_lengths:
    #I would like to add 3 to each element of these lists which are values.
    test[i][j for j in test[i]] += i

【问题讨论】:

  • 哪些行会触发语法错误
  • 我附上了一些虚拟变量。它只是一个整数列表。我在test[i][j for j in test[length]] += 3 行收到语法错误。
  • length 没有定义,没有这个变量
  • 抱歉,我已将其更改为i,以便删除任何变量含义。
  • 你的问题还不清楚。您希望修改字典后的结果是什么?

标签: python list dictionary defaultdict


【解决方案1】:

假设你想就地修改列表,你需要覆盖每个元素,因为整数是不可变的:

test[4][:] = [e+3 for e in test[4]]

输出:

defaultdict(list, {4: [4, 8, 9]})

如果您不关心生成新对象(即您没有将变量名链接到test[4],您可以使用:

test[4] = [e+3 for e in test[4]]

有什么区别?

第一种情况修改了列表。如果其他变量指向列表,则将反映更改:

x = test[4]
test[4][:] = [e+3 for e in test[4]]
print(x, test)
# [4, 8, 9] defaultdict(<class 'list'>, {4: [4, 8, 9]})

在另一种情况下,列表被替换为一个新的、独立的、。所有潜在的绑定都丢失了:

x = test[4]
test[4] = [e+3 for e in test[4]]
print(x, test)
# [1, 5, 6] defaultdict(<class 'list'>, {4: [4, 8, 9]})

在你的循环中

假设run_lengths 包含要更新的键列表:

for i in run_lengths:
    test[i][:] = [e+3 for e in test[i]]

【讨论】:

  • 我有没有办法用我现有的 for 循环设置来实现这一点?
  • @Hamish 查看更新
  • 非常感谢!在我接受您的回答之前,您能否让我了解您所说的“生成新对象”是什么意思?这段代码只是一个辅助项目的一些数据分析,但我很想知道这种方法的正确方法或细微差别。
  • 我提供了一个示例来了解更新列表和替换为新列表之间的区别
  • 是的,这是正确的
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 2022-11-27
  • 1970-01-01
  • 2022-01-20
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多