简体   繁体   English

从两个列表创建嵌套列表

[英]Create nested list from two lists

I have got two lists like this:我有两个这样的列表:

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

I need to create a list of lists like this:我需要创建一个像这样的列表列表:

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

I have done this:我已经这样做了:

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]])

Just wondering if there is a more Pythonic way of doing this.只是想知道是否有更 Pythonic 的方式来做到这一点。

Using zip and list comprehension is another way to do it.使用zip和列表理解是另一种方法。 ie, by doing l.extend([list(a) for a in zip(f, t)]) :即,通过执行l.extend([list(a) for a in zip(f, t)])

Demo:演示:

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

不确定我喜欢它,但是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM