如何压缩长度不均匀的列表

时间:2014-06-06 10:59:29

标签: python python-2.7 list-comprehension

我有3个名单。

>>> a = [1,2,3,4,5]
>>> b = ['a','b','c','d']
>>> c = ['x','y','z'] 

我希望以不遗漏任何元素的方式压缩它们。 python中是否存在可以执行以下任务的函数?

>>> myzip(a,b,c)
[(1, 'a','x'), (2, 'b','y'), (3, 'c','z'), (4,'d'), (5)]

提前致谢!!

3 个答案:

答案 0 :(得分:4)

您可以使用itertools.izip_longest并列出这样的列表理解

from itertools import izip_longest
print [tuple(j for j in i if j is not None)for i in izip_longest(a, b, c)]
# [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (4, 'd'), (5,)]

答案 1 :(得分:1)

from itertools import izip_longest

a = [1,2,3,4,5]
b = ['a','b','c','d']
c = ['x','y','z']
print list(izip_longest(a,b,c))
[(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (4, 'd', None), (5, None, None)]

您还可以指定其他fillvalueNone是默认值:

print list(izip_longest(a, b, c,fillvalue=0))
[(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (4, 'd', 0), (5, 0, 0)]

答案 2 :(得分:0)

a=[1,2,3,4]
b=[1,2]
c=[1]

print map(None,a,b,c)


#output [(1, 1, 1), (2, 2, None), (3, None, None), (4, None, None)]

print [tuple(j for j in i if j)for i in map(None,a,b,c)]
#output [(1, 1, 1), (2, 2), (3,), (4,)]