我有一个包含列索引的列表,如下所示:
list1 = [0 ,2]
Run Code Online (Sandbox Code Playgroud)
另一个列表列表将包含csv文件的文件内容,如下所示:
list2=[["abc", 1, "def"], ["ghi", 2, "wxy"]]
Run Code Online (Sandbox Code Playgroud)
什么是创建新列表的最佳方法,该列表仅包含来自ie list2中包含的列号的值list1
newList = [["abc", "def"], ["ghi", "wxy"]]
Run Code Online (Sandbox Code Playgroud)
我很难创建子列表
如果您对元组列表感到满意,可以使用 operator.itemgetter
import operator
list1 = [0,2]
my_items = operator.itemgetter(*list1)
new_list = [ my_items(x) for x in list2 ]
Run Code Online (Sandbox Code Playgroud)
(或者你可以map在这里使用):
new_list = map(my_items, list2)
Run Code Online (Sandbox Code Playgroud)
并作为1班轮:
new_list = map(operator.itemgetter(*list1), list2)
Run Code Online (Sandbox Code Playgroud)
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']]
Run Code Online (Sandbox Code Playgroud)
你可以使用List Comprehension: -
newList = [[each_list[i] for i in list1] for each_list in list2]
Run Code Online (Sandbox Code Playgroud)
从 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']]
Run Code Online (Sandbox Code Playgroud)
我希望这也有帮助!