Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing elements from list of list of strings

Tags:

python

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

I have a list that looks like above.

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

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

I think I can do it by going over the whole list and add only the second element to a new list like:

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

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

like image 381
Dawn17 Avatar asked Mar 22 '18 19:03

Dawn17


2 Answers

You can use a list comprehension:

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

Output:

['abc', 'bcd', 'cde']
like image 78
Ajax1234 Avatar answered Nov 06 '22 02:11

Ajax1234


Another way to do it is to use itemgetter from operator module:

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 cast it to list:

result = list(list(zip(*l))[1])
like image 38
Vasilis G. Avatar answered Nov 06 '22 04:11

Vasilis G.