2014-07-17 45 views
2

我有两个列表这样创建嵌套列表:从两个列表

t = [1,2,3,4] 
f = ['apples', 'oranges','grapes','pears'] 

我需要创建一个列表的列表如下:

data = [ 
     ['Fruit', 'Total'], 
     ['apples', 1], 
     ['oranges', 2], 
     ['grapes', 3], 
     ['pears' 4] 
    ] 

我已经做到了这一点:

l = [] 
l.append(['Fruit', 'Total']) 
# I guess I should have check that lists are the same size? 
for i, fruit in enumerate(f): 
    l.append([fruit, t[i]]) 

只是想知道是否有更多的Pythonic这样做。

+0

'打印拉链(F,T)'你可能感兴趣的,虽然它返回一个元组列表 - 未列出的清单。 – alfasin

回答

5

使用zip和列表理解是另一种方式来做到这一点。即,通过做l.extend([list(a) for a in zip(f, t)])

演示:

>>> t = [1,2,3,4] 
>>> f = ['apples', 'oranges','grapes','pears'] 
>>> l = [] 
>>> l.append(['Fruit', 'Total']) 
>>> l.extend([list(a) for a in zip(f, t)]) 
>>> l 
[['Fruit', 'Total'], ['apples', 1], ['oranges', 2], ['grapes', 3], ['pears', 4]] 
>>> 
+0

诗意!真... –

0

不知道我喜欢它,但:

r = [[f[i], t[i]] if i >= 0 else ['fruit', 'total'] for i in range(-1, len(t))]