问题
I have an input stream that looks something like this:
data = [[1,234],[2,432],[3,443]]
I'm trying to figure the best way to get the second element of every list. I can easily get the second value of a single entry by something like data[0][1]
, or every list in a range with both elements by using data[0:2]
, but I can't for the life of me figure out how to get just the second element from every array, short of processing every element independently through an array and making a new one on the side. That is an ugly solution, is there a better one out there? Thanks!
回答1:
Use a list comprehension:
[lst[1] for lst in data]
回答2:
or use operator and map:
from operator import itemgetter
map(itemgetter(1), data)
来源:https://stackoverflow.com/questions/13380993/properly-slicing-a-list-of-lists