简体   繁体   English

在Python中提取列表列表的特定元素

[英]Extracting specific elements of a list of lists in Python

Here's a list: 这是一个清单:

foo=[(1, 2, {'weight': 1}), (1, 3, {'weight': 2}), (1, 4, {'weight': 3}), (`1 5, {'weight': 4}), (1, 6, {'weight': 5}), (1, 7, {'weight': 6})]

Say I wanted to extract a particular element of each list within foo and store it in a separate list. 假设我想在foo中提取每个列表的特定元素并将其存储在单独的列表中。

eg I wanted to extract 2nd element from each list, within foo and save it in the array labelled bar. 例如,我想从foo中的每个列表中提取第二个元素,并将其保存在标记为bar的数组中。

bar=[2,3,4,5,6,7]

How can this be done in Python 2.7x? 如何在Python 2.7x中完成?

>>> from operator import itemgetter
>>> map(itemgetter(1), foo))
[2, 3, 4, 5, 6, 7]

You can do that as: 你可以这样做:

bar = [i[1] for i in foo]
>>> print bar
[2,3,4,5,6,7]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从列表python 2.7中提取特定元素 - Extracting specific elements from list python 2.7 使用列表理解从python中的列表字典中提取列表元素 - Extracting list elements from dictionary of lists in python using list comprehension 从 Python 字符串列表中提取特定元素的子列表 - Extracting sublists of specific elements from Python lists of strings 按元素中的特定值将python列表拆分为列表 - Split python list into lists by a specific value in elements Python 清除列表列表中的特定元素 - Python Clean Specific Elements in List of Lists "Python:根据文本上的元素创建列表并提取特定值" - Python: Create a list based on elements on text and extracting specific values 如何将特定索引的列表元素更改为在列表列表中浮动(Python)? - How to change list elements of specific indices to float in a list of lists (Python)? 从数据框中的列表列表中提取元素 - Extracting elements from Lists of List in a data frame 通过从其他两个列表中提取连续元素,将元素添加到Python 3.3中的列表中 - Adding elements to a list in Python 3.3 by extracting consecutive elements from two other lists 如何使用特定元素在python中打印列表列表的每个元素 - How to print each element of a list of lists in python using the specific elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM