我正在编写一个脚本来处理数据,所以我有一个包含计算值字典的列表。一旦我计算出新的,我想在适当的字典中附加新条目。
我知道我可以使用列表或 np 数组来做到这一点,但我想学习如何使用字典。我也刚开始使用列表推导,所以我想更好地了解如何正确使用它。所以让自己的生活变得艰难。
这是简化的示例。
我计算值并将它们放入字典中,然后将其放入列表中以对应每个条目。
A=[{'low':1},{'low':2}]
print(A)
[{'low': 1}, {'low': 2}] # entry 0 corresponds to sample 1 and the next to sample 2
B=[{'hi':1},{'hi':2}]
print(B)
[{'hi': 1}, {'hi': 2}] # entry 0 corresponds to sample 1 and the next to sample 2
C=[{}]*len(A) # initialize list to contain a dictionary for each sample. Each dictionary will receive the corresponding values copied from A and B
print(C)
[{}, {}]
现在我尝试使用字典推导
{C[x].update(A[x]) for x in range(len(A))}
print(C)
[{'low': 2}, {'low': 2}]
结果不是我所期望的。我想要这样的东西:
[{'low':1,'high':1},{'low':1,'high':1}]
我在这里不明白什么...
谢谢