Python-从列表中提取特定列

时间:2012-09-26 20:19:47

标签: python

我有一个包含列索引的列表,如下所示:

list1 = [0 ,2]

另一个列表列表将包含csv文件的文件内容,如下所示:

list2=[["abc", 1, "def"], ["ghi", 2, "wxy"]]

创建新列表的最佳方法是什么,该列表仅包含来自list2的值list1中包含的列号,即

newList = [["abc", "def"], ["ghi", "wxy"]]

我很难创建子列表

6 个答案:

答案 0 :(得分:8)

如果您对元组列表感到满意,可以使用operator.itemgetter

import operator
list1 = [0,2]
my_items = operator.itemgetter(*list1)
new_list = [ my_items(x) for x in list2 ]

(或者你可以在这里使用map):

new_list = map(my_items, list2)

并作为1班轮:

new_list = map(operator.itemgetter(*list1), list2)

operator.itemgetter可能比嵌套列表推导具有轻微的性能优势,但它可能足够小,以至于不值得担心。

答案 1 :(得分:7)

>>> list1 = [0 ,2]
>>> list2=[["abc", 1, "def"], ["ghi", 2, "wxy"]]
>>> newList = [[l[i] for i in list1] for l in list2]
>>> print newList
[['abc', 'def'], ['ghi', 'wxy']]

答案 2 :(得分:7)

您可以使用List Comprehension: -

newList = [[each_list[i] for i in list1] for each_list in list2]

答案 3 :(得分:2)

如果您正在使用csv文件,则无需重新发明轮子。 看看优秀的csv模块。

答案 4 :(得分:2)

无法从python列表中直接提取某些列,因为python并不认为此列表是数组(按定义具有行和列),而是列表列表。

但是,通过使用Numpy,您可以非常轻松地执行类似的操作,而无需使用任何列表理解。具体来说,您可以执行以下操作:

import numpy as np

list1 = [0 , 2]
list2=[["abc", 1, "def"], ["ghi", 2, "wxy"]]

# Covert list2 to numpy array
array2 = np.array(list2)

# Extract the specific columns from array2 according to list1
newArray = array2[:, list1]

#  Convert the new numpy array to list of lists
newList = newArray.tolist()

# newList is the following list: [['abc', 'def'], ['ghi', 'wxy']]

我希望这也会有所帮助!

答案 5 :(得分:0)

您可以将Poete Maudit's answer放在一行中,如下所示:

column = np.array(list_name)[:,column_number].tolist()

您还可以通过删除.tolist()

将其保留为numpy数组。
相关问题