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.
Using zip and list comprehension is another way to do it. i.e., by doing 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]]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With