简体   繁体   中英

append list elements into nested list using list comprehension

I have a list with years [1745,1742,1743,1730,1739] and another nested list [['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration']]

I am trying to append the first list year values into the last place of the nested list using list comprehension .

required output: 
[['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration', 1745], 
 ['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA', 'Pro-Administration', 1742]]

I tried but I couldn't figure it out. Thank you.

You can use zip to pair the two lists:

y = [1745,1742,1743,1730,1739]
l = [['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration'],
 ['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA', 'Pro-Administration']]
print([s + [n] for s, n in zip(l, y)])

This outputs:

[['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration', 1745], ['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA', 'Pro-Administration', 1742]]

A list comprehension creates a new list. If you want to mutate an existing list, use list.append() :

lst1 = [1745,1742,1743,1730,1739]
lst2 = [['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE',
         'Anti-Administration'],
        ['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA',
         'Pro-Administration']]
for year, data in zip(lst1, lst2):
    data.append(year)

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.

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