在python中将不平等的列表压缩到不会将任何元素从较长列表中删除的列表中 [英] Zipping unequal lists in python in to a list which does not drop any element from longer list being zipped
本文介绍了在python中将不平等的列表压缩到不会将任何元素从较长列表中删除的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表
a = [1,2,3]
b = [9,10]
我想将这两个列表组合(zip)到一个列表中 c
,使得
I want to combine (zip) these two lists into one list c
such that
c = [(1,9), (2,10), (3, )]
Python中的标准库中是否有任何功能?
Is there any function in standard library in Python to do this?
推荐答案
您要寻求的是 itertools.izip_longest
What you seek is itertools.izip_longest
>>> a = [1,2,3]
>>> b = [9,10]
>>> for i in itertools.izip_longest(a,b): print i
...
(1, 9)
(2, 10)
(3, None)
编辑1 :如果你真的想摆脱无
s,那么你可以尝试:
EDIT 1: If you really want to get rid of the None
s, then you could try:
>>> for i in (filter(None, pair) for pair in itertools.izip_longest(a,b)): print i
(1, 9)
(2, 10)
(3,)
编辑2 :回应steveha的评论:
EDIT 2: In response to steveha's comment:
filter(lambda p: p is not None, pair) for pair in itertools.izip_longest(a,b)
这篇关于在python中将不平等的列表压缩到不会将任何元素从较长列表中删除的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文