列出列表中每个列表的特定位置 (python)
List a specific position in each list within a list (python)
有没有办法 select 矩阵中的每第二个或第三个(例如)项目?
例如:
f = [["1", "5", "8", "9"], ["2", "6", "9", "10"], ["3", "7", "11", "12"]]
我想知道是否有直接函数 select 每个列表中的每个第二个数字(最好也将这些数字也放在列表中)。因此导致:
["5", "6", "7"]
我知道我可以使用循环实现这个但是我想知道我是否可以直接实现这个。
没有任何循环(外部)
>>> 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']
参考:map
另一种不用循环的方法(礼貌:)
>>> import operator
>>> list(map(operator.itemgetter(1), f))
['5', '6', '7']
参考:itemgetter
另一种不用循环的方法(礼貌:)
>>> list(zip(*f)[1])
['5', '6', '7']
参考:zip
seconds = [x[1] for x in f]
您可以使用列表理解:
i = 1 # Index of list to be accessed
sec = [s[i] for s in f if len(s) > i]
此代码还将检查每个子列表中的索引是否为有效值。
有没有办法 select 矩阵中的每第二个或第三个(例如)项目?
例如:
f = [["1", "5", "8", "9"], ["2", "6", "9", "10"], ["3", "7", "11", "12"]]
我想知道是否有直接函数 select 每个列表中的每个第二个数字(最好也将这些数字也放在列表中)。因此导致:
["5", "6", "7"]
我知道我可以使用循环实现这个但是我想知道我是否可以直接实现这个。
没有任何循环(外部)
>>> 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']
参考:map
另一种不用循环的方法(礼貌:
>>> import operator
>>> list(map(operator.itemgetter(1), f))
['5', '6', '7']
参考:itemgetter
另一种不用循环的方法(礼貌:
>>> list(zip(*f)[1])
['5', '6', '7']
参考:zip
seconds = [x[1] for x in f]
您可以使用列表理解:
i = 1 # Index of list to be accessed
sec = [s[i] for s in f if len(s) > i]
此代码还将检查每个子列表中的索引是否为有效值。