简体   繁体   中英

Python: how can I get rid of the second element of each sublist?

I have a list of sublists, such as:

[[501, 4], [501, 4], [501, 4], [501, 4]]

How can I get rid of the second element for each sublist ? (ie 4)

[501, 501, 501, 501]

Should I iterate the list or is there a faster way ? thanks

You can use a list comprehension to take the first element of each sublist:

xs = [[501, 4], [501, 4], [501, 4], [501, 4]]
[x[0] for x in xs]
# [501, 501, 501, 501]
a = [[501, 4], [501, 4], [501, 4], [501, 4]]
b = [c[0] for c in a]

A less pythonic, functional version using map :

a = [[501, 4], [501, 4], [501, 4], [501, 4]]
map(lambda x: x[0], a)

Less pythonic, since it does not use list comprehensions. See here .

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