这是我正在编写的部分代码。我的目标是从空列表 D_E
开始,然后累加 de
的结果进入D_E
,来自for
循环。
D_E = []
for num_flip in range (0, N):
probsu = []
de = []
for i in range (L):
probsui = []
for j in range (nuni):
counts = results.get_counts((nuni*i)+j)
prob = absorb_counts(counts)[num_flip]/sum(counts.values())
probsui.append(prob)
pz_bar = np.average(probsui)
probsu.append(pz_bar)
de.append(np.abs(5 - math.comb(N, num_flip)))
spec = dict(zip(EW,probsu))
# Here, I want to perform an iterative update of D_E
D_E = list(map(add, D_E, de))
D_E = dict(zip(EW, [0.5*i for i in D_E]))
print(D_E)
我初始化了D_E
是一个空列表,在我的 for
中循环 num_flip
,我正在尝试更新D_E
通过添加de
,另一个 list 。我不会附加 de
,但想将其所有元素添加到 D_E
。由于我正在重复此过程,我想知道是否可以使用 map
在 for 循环中,并更新 D_E
。然而,目前我的最终结果是D_E
只是 {}
。我不知道我哪里做错了。
我尝试了一个更简单的示例:D_E = dict(zip([1,2,3], [0.5*i for i in [1,2,3]]))
效果很好,我想知道如何使用 map
在我的例子中的 for 循环中?
最佳答案
根据评论的讨论,您需要在对新值求和之前初始化D_E
。以下代码应该可以工作(我将其余代码保留原样,甚至是从未使用过的部分,例如 spec
)。
D_E = [0 for _ in range(L)]
for num_flip in range (0, N): # Note: range normally starts from 0, so range(N) is enough
probsu = []
de = []
for i in range (L):
probsui = []
for j in range (nuni):
counts = results.get_counts((nuni*i)+j)
prob = absorb_counts(counts)[num_flip]/sum(counts.values())
probsui.append(prob)
pz_bar = np.average(probsui)
probsu.append(pz_bar) # Note: this is never used
de.append(np.abs(5 - math.comb(N, num_flip)))
spec = dict(zip(EW,probsu)) # Note: this is never used
# Here, I want to perform an iterative update of D_E
D_E = list(map(add, D_E, de))
D_E = dict(zip(EW, [0.5*i for i in D_E]))
print(D_E)
关于python - 我可以使用map对列表进行迭代更新吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70383641/