简体   繁体   中英

Add values from list into nested lists

Im total beginner and I´d like to ask, how can add values from list age into the list n_list.

n_lst = [['Peter', 'Brown'], ['Thomas', 'Black'], ['Andy', 'Green']]
age = [33, 35, 28]

What I need to get:

[['Peter', 'Brown', 33], ['Thomas', 'Black', 35], ['Andy', 'Green', 28]]

Thank you a lot for your help!

lst = [['Peter', 'Brown'], ['Thomas', 'Black'], ['Andy', 'Green']] 
age = [33, 35, 28]

new_lst = [p + [a] for p, a in zip(lst, age)]

Inplace modification:

for p, a in zip(lst, age):
  p.append(a)

print(lst)
n_lst = [['Peter', 'Brown'], ['Thomas', 'Black'], ['Andy', 'Green']]
age = [33, 35, 28]

for i in range(len(age)):
        n_lst[i].append(age[i])


There are 3 straightforward options here (and plenty of more complicated ones)

  1. For each list in the nested list, append the item from the age list with the same index:

     for index, subList in enumerate(n_lst): subList.append(age[index])

For each item in a list, enumerate gives you both the numeric position of the item and the item itself. We can use this to pick out the corresponding age with ease.

  1. Get a number corresponding to the index of each item in the age list, and use that to identify the sub list that we want to append the age to. Sounds the same, and has the same result, but always looks a little messier to me:

     for i in range(len(age)): n_lst[i].append(age[i])
  2. Create a new list with the collated information in it:

     lst = [subList + [year] for subList, year in zip(lst, age)]

zip() returns an iterator of tuples from the objects passed to it. I would try and avoid worrying about what that means at this point.

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