gpt4 book ai didi

python - 从两个yield函数更新字典

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:24 25 4
gpt4 key购买 nike

假设我有两个函数,它们都产生字典:

def one_two_three():
myDict1 = {}
myList1 = range(1, 4)
for i in myList1:
myDict1['number'] = i
yield myDict1

def four_five_six():
myDict2 = {}
myList2 = range(4, 7)
for i in myList2:
myDict2['other_number'] = i
yield myDict2

有没有办法调用这两个函数并更新字典以返回如下数据结构:

{'number': 0, 'other_number': 3}
{'number': 1, 'other_number': 4}
{'number': 2, 'other_number': 5}

最佳答案

是的,但作为更好的方法,您可以生成键的元组并将其值 zip 生成器并使用列表理解创建预期的字典:

def one_two_three():
myList1 = range(0, 4)
for i in myList1:
yield 'number',i

def four_five_six():
myList2 = range(3, 6)
for i in myList2:
yield 'other_number',i


print [{i:j,k:z} for (i,j),(k,z) in zip(one_two_three(),four_five_six())]

输出:

[{'number': 0, 'other_number': 3},
{'number': 1, 'other_number': 4},
{'number': 2, 'other_number': 5}]

作为一种更Pythonic的方式,无需使用生成器函数,您可以压缩范围对象并使用列表理解创建字典:

>>> [{'number':i,'other_number':j} for i,j in zip(range(0,4),range(3,6))]
[{'number': 0, 'other_number': 3},
{'number': 1, 'other_number': 4},
{'number': 2, 'other_number': 5}]

关于python - 从两个yield函数更新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35118803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com