好吧,所以说我有一个用于生成字典的for循环,该如何将字典存储在列表中,然后在列表中进行迭代并提取字典,我知道这有点令人困惑,因此这里是一个示例
for _ in 10:
DB = {}
DB["x"] = 1
DB["y"] = 2
DB["z"] = 3
StoreDBInList(DB)
然后我可以迟到
for DB in list:
print(DB["x"])
print(DB["y"])
print(DB["z"])
在循环外初始化列表。追加到循环内的列表。稍后在循环中迭代列表时,每个元素都是您之前创建的字典。
lst = []
for i in range(3):
dct = {'x': i, 'y': (i+1), 'z': (i+2)}
lst.append(dct)
print(lst)
# [{'x': 0, 'y': 1, 'z': 2}, {'x': 1, 'y': 2, 'z': 3}, {'x': 2, 'y': 3, 'z': 4}]
for dct in lst:
print(dct['x'])
print(dct['y'])
print(dct['z'])
# 0
# 1
# 2
# 1
# 2
# 3
# 2
# 3
# 4
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句