Parsing items from a list of strings

list = [[1,'abc'], [2, 'bcd'], [3, 'cde']]

I have a list that looks higher.

I want to parse a list and try to get a list containing only the second element of all lists.

output = ['abc','bcd','cde']

I think I can do this by going through the entire list and adding only the second element to the new list, for example:

 output = [] for i in list: output.append(i[1]) 

something like this, but please tell me if there is a better way.

+5
source share
2 answers

You can use list comprehension:

 l = [[1,'abc'], [2, 'bcd'], [3, 'cde']] new_l = [b for _, b in l] 

Output:

 ['abc', 'bcd', 'cde'] 
+7
source

Another way to do this is to use the itemgetter module from operator :

 from operator import itemgetter l = [[1,'abc'], [2, 'bcd'], [3, 'cde']] result = list(map(itemgetter(1), l)) print(result) 

Output:

 ['abc', 'bcd', 'cde'] 

Another not-so-elegant way is to use the zip function, take the second element from the newly created list and pass it to list :

 result = list(list(zip(*l))[1]) 
+3
source

Source: https://habr.com/ru/post/1276027/


All Articles