在列表中的每个列表中列出特定位置(python) [英] List a specific position in each list within a list (python)

查看:458
本文介绍了在列表中的每个列表中列出特定位置(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以选择矩阵中的每个第二个或第三个(例如)项?

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

例如:

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.

推荐答案

无任何循环(外部)

>>> 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

Ref : map

另一种无循环的方式(礼貌:

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

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

参考: itemgetter

另一种无循环的方法(礼貌:

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

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

参考: zip

这篇关于在列表中的每个列表中列出特定位置(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆