是否存在语法上简短的方法?
['a','b','c'] and [[1,2],[1],[1,2,3]] -> [['a', [1,2]], ['b', [1]], ['c',[1,2,3]]]
答案 0 :(得分:3)
您正在寻找zip
:
>>> a = ['a','b','c']
>>> b = [[1,2],[1],[1,2,3]]
>>> list(zip(a, b))
[('a', [1, 2]), ('b', [1]), ('c', [1, 2, 3])]
如果你真的希望元素是列表而不是元组,那么你也可以这样做:
>>> [list(t) for t in zip(a,b)]
[['a', [1, 2]], ['b', [1]], ['c', [1, 2, 3]]]
答案 1 :(得分:0)
您正在寻找: [zip(a,b)中x的列表(x)]
较短版本:map(list,zip(a,b))
这将解释一些事情:
>>> a = ['a','b','c']
>>> b = [[1,2],[1],[1,2,3]]
>>> c = zip(a, b)
>>> c
[('a', [1, 2]), ('b', [1]), ('c', [1, 2, 3])]
>>> d = [list(x) for x in c]
>>> d
[['a', [1, 2]], ['b', [1]], ['c', [1, 2, 3]]]
答案 2 :(得分:0)
拉链+列表+地图
result = map(list,zip(a,b))
答案 3 :(得分:0)
如果列表大小相同,您也可以使用enumerate
:
l1 = ['a','b','c']
l2 = [[1,2],[1],[1,2,3]]
[[ele,l2[ind]]for ind, ele in enumerate(l1)]
[['a', [1, 2]], ['b', [1]], ['c', [1, 2, 3]]]
如果您有不同的尺寸列表,则可以使用itertools.izip_longest
l1 = ['a','b','c','d']
l2 = [[1,2],[1],[1,2,3]]
from itertools import izip_longest
print [list(x) for x in izip_longest(l1,l2,fillvalue="No data")]
[['a', [1, 2]], ['b', [1]], ['c', [1, 2, 3]], ['d', 'No data']]