List a specific position in each list within a list (python)

有些话、适合烂在心里 提交于 2019-12-11 13:18:08

问题


Is there a way to select every 2nd or 3rd (for example) item within a matrix?

For example:

f = [["1", "5", "8", "9"], ["2", "6", "9", "10"], ["3", "7", "11", "12"]]

I am wondering if there is a direct function to select every 2nd number in every list (preferably putting those digits in a list as well). Thus resulting into:

["5", "6", "7"]

I know that I can achieve this using a loop but I am wondering if I can achieve this directly.


回答1:


Without any loop (external)

>>> f = [["1", "5", "8", "9"], ["2", "6", "9", "10"], ["3", "7", "11", "12"]]
>>> list(map(lambda x:x[1],f))  # In python2, The list call is not required
['5', '6', '7']

Ref : map

Another way to do it without loop (Courtesy : Steven Rumbalski)

>>> import operator
>>> list(map(operator.itemgetter(1), f))
['5', '6', '7']

Ref: itemgetter

Yet another way to do it without loop (Courtesy : Kasra A D)

>>> list(zip(*f)[1])
['5', '6', '7']

Ref: zip




回答2:


Try list comprehension:

seconds = [x[1] for x in f]



回答3:


You may use list comprehension:

i = 1  # Index of list to be accessed
sec = [s[i] for s in f if len(s) > i]

This code will also check in each sublist whether the index is a valid value or not.



来源:https://stackoverflow.com/questions/28750063/list-a-specific-position-in-each-list-within-a-list-python

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