I have a list of lists:
[['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
How can I merge it with a single list like:
['800','854','453']
So that the end result looks like:
[['John', 'Sergeant', '800'], ['Jack', 'Commander', '854'], ['Jill', 'Captain', '453']]
Initially I tried: zip(list_with_lists,list)
but data was obfuscated
a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
b = ['800', '854', '453']
c = [x+[y] for x,y in zip(a,b)]
print c
Result:
[['John', 'Sergeant ', '800'], ['Jack', 'Commander ', '854'], ['Jill', 'Captain ', '453']]
Solution with enumerate
instead of zip
:
a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
b = ['800','854','453']
c = [a[i]+[bi] for i,bi in enumerate(b)]
Using zip
is definitely the more pythonic solution in this particular case. However, sometimes you want have access to indices (yes, even in Python), so it's useful to know about enumerate
too.
range
instead of zip
a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
b = ['800','854','453']
c = [a[x]+[b[x]] for x in range(len(b))]
print c
or update original list:
[a[x].append(b[x]) for x in range(3)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.