从两个列表创建嵌套列表

时间:2014-07-17 05:44:50

标签: python

我有两个这样的列表:

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方式来做到这一点。

2 个答案:

答案 0 :(得分:6)

使用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]]
>>>

答案 1 :(得分:0)

不确定我喜欢它,但是:

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