简体   繁体   中英

Retrieving the first element of a list nested in another list

I have the following code:

addresses = [['Jim', 543, 65], ['Jack', 4376, 23], ['Hank', 764, 43]]
print addresses[0:][0]  # I want this to return: ['Jim', 'Jack', 'Hank']`

How would I make this print out only the names in addresses ?

I used this:

for item in addresses:
    print item[0]

One more solution with map :

print(list(map(lambda x: x[0], addresses)))
['Jim', 'Jack', 'Hank']

Or you could use operator.itemgetter(0) as @Kupiakos suggested in the comment:

from operator import itemgetter(0)
print(list(map(itemgetter(0), addresses)))
['Jim', 'Jack', 'Hank']

Timing :

In [648]: %timeit list(map(operator.itemgetter(0), addresses))
1000000 loops, best of 3: 1.16 µs per loop

In [649]: %timeit list(map(lambda x: x[0], addresses))
1000000 loops, best of 3: 1.25 µs per loop
from operator import itemgetter
print(map(itemgetter(0), addresses))

This selects the first item from each element in addresses and creates a new list from it. itemgetter(0) is faster than a lambda.

print("\n".join(zip(*addresses)[0]))
#or maybe just 
print(zip(*addresses)[0]) 

might as well throw one more into the ring :P

print([x[0] for x in addresses])

最简单的方法是使用列表理解

names = [a[0] for a in addresses]

You can use a list comprehension to get the first item ( item[0] ) from each list in your address list. Then you just print it. From the REPL:

>>> addresses = [['Jim', 543, 65], ['Jack', 4376, 23], ['Hank', 764, 43]]
>>> [item[0] for item in addresses]
['Jim', 'Jack', 'Hank']
>>> for name in [item[0] for item in addresses]:
...     print(name) 
... 
Jim
Jack
Hank

Python's print lets you shorthand this to:

print([item[0] for item in addresses])

You can use a list comprehension :

>>> names = [sublist[0] for sublist in addresses]
>>> names
['Jim', 'Jack', 'Hank']

You want this:

print [a[0] for a in addresses]

Here a is a subarray and a[0] is its first element.

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