簡體   English   中英

Python-從列表中提取特定列

[英]Python- Extract specific columns from list

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

list1 = [0 ,2]

另一個列表列表將包含csv文件的文件內容,如下所示:

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

什么是創建新列表的最佳方法,該列表僅包含list2中包含list1中包含的列號的list1

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

我很難創建子列表

如果您對元組列表感到滿意,可以使用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可能比嵌套列表推導具有輕微的性能優勢,但它可能足夠小,不值得擔心。

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

您可以使用List Comprehension : -

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

如果您正在使用csv文件,則無需重新發明輪子。 看看優秀的csv模塊。

直接從python列表列表中直接提取某些列是不可能的,因為python不會將此列表視為數組(按定義行和列),而是將其視為列表列表。

但是,通過使用Numpy ,您可以非常輕松地執行此類操作,而無需使用任何列表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']]

我希望這也有幫助!

您可以將Poete Maudit的答案放入一行,如下所示:

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

您還可以通過刪除.tolist()將其保留為numpy數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM