Reputation: 818
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?
Upvotes: 1
Views: 3951
Reputation: 26580
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']
Upvotes: 5
Reputation: 133514
>>> items = ['32 2 6 6', '31 31 31 6', '31 2 6 6']
>>> [s.partition(' ')[0] for s in items]
['32', '31', '31']
Upvotes: 0