简体   繁体   中英

print the first item in list of lists

I am trying to print the first item in a list of lists. This is what I have:

My list is like this:

['32 2 6 6', '31 31 31 6', '31 2 6 6']

My code is:

from operator import itemgetter

contents = []
first_item = list(map(itemgetter(0), contents))
print first_item

but itemgetter only returns: ['3', '3', '3'] istead of ['32', '31', '31'] can I use a delimiter?

You are dealing with a list of strings, so you are getting the first index of each string, which is in fact 3 for all of them. What you should do is a comprehension where you split each string on space (which is the default of split) and get the first index:

first_element = [s.split(None, 1)[0] for s in contents]

Inside the comprehension, the result of each s.split(None, 1) will actually be =>

['32', '2 6 6'] ['31', '31 31 6'] ['31', '2 6 6']

and you get the first index of that.

Output:

['32', '31', '31']
>>> items = ['32 2 6 6', '31 31 31 6', '31 2 6 6']
>>> [s.partition(' ')[0] for s in items]
['32', '31', '31']

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