从两个yield函数

时间:2016-01-31 20:04:10

标签: python dictionary generator

假设我有两个功能,yield词典:

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}

1 个答案:

答案 0 :(得分:1)

是的但是作为一种更好的方法,你可以产生密钥的元组并将它们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}]