假设我有两种类型的迭代,其中一种是列表,另一种是生成器对象(或者如果它更容易作为列表查看)
该列表具有以下元素:list = [1,2,3,4,5,6,7,8,9]
另一方面,生成器在每次迭代中生成一个元组列表,得出的列表如下所示:ylist = [(3,"three"),(4,"four"),(5,"five")]
。
我希望能够获得一个如下所示的列表:finallist = [1,2,(3,"three"),(4,"four"),(5,"five"),6,7,8,9]
。
我如何实现这一目标?
答案 0 :(得分:4)
将该生成器的返回项转换为dict,然后使用列表推导:
>>> lis = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ylist = [(3, "three"),(4, "four"),(5, "five")]
>>> dic = dict(ylist)
>>> [x if x not in dic else (x, dic[x]) for x in lis]
[1, 2, (3, 'three'), (4, 'four'), (5, 'five'), 6, 7, 8, 9]