1

假设我有两种类型的可迭代对象,一种是列表,另一种是生成器对象(或者如果更容易将两者都视为列表)

该列表具有以下元素: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].

我如何实现这一目标?

4

1 回答 1

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]
于 2013-07-08T00:28:24.800 回答