Properly slicing a list of lists

﹥>﹥吖頭↗ 提交于 2019-12-24 11:07:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!