【发布时间】:2019-02-25 16:01:03
【问题描述】:
我正在尝试将元素附加到循环中的多个字典键。但是,现在我认为要做到这一点还有很长的路要走 - 每个密钥更新都需要单独一行,例如:
# My dictionary
my_dict = {'Key1': [0], 'Key2': [0], 'Key3': [0]}
# Show initial state
print(my_dict)
# Populate dictionary with new elements
for i in range(1, 5):
my_dict['Key1'].append(i)
my_dict['Key2'].append(-i)
my_dict['Key3'].append(i^2)
# Show final result
print(my_dict)
给你想要的
{'Key1': [0, 1, 2, 3, 4], 'Key2': [0, -1, -2, -3, -4], 'Key3': [0, 3, 0, 1, 6]}
但是,我想做的是将所有这些新元素附加到一行中,就像这样:
for i in range(1, 5):
my_dict['Key1', 'Key2', 'Key3'].append(i, -i, i^2)
【问题讨论】:
-
这有什么改进?
-
@KlausD。假设我没有三把钥匙,而是一百把。我不想写一百行来为键提供新元素。我想在一行中只输入一个数组或一个列表。
-
如果你有一百个键,你可能会使用某种循环而不是复制/粘贴 100 条几乎相同的行。在一行中对 100 个不同的键执行 100 次附加操作很难读取,不是吗?
-
在某些时候,您必须定义数百个键及其数百个表达式。
-
差不多。我可能会创建一个像
{'Key1': lambda i: i, 'Key2': lambda i: -i, 'Key3': lambda i: i^2}这样的函数的字典并循环遍历该字典。
标签: python loops dictionary append