Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从列表中删除索引列表_Python_Python 3.x_List - Fatal编程技术网

Python 如何从列表中删除索引列表

Python 如何从列表中删除索引列表,python,python-3.x,list,Python,Python 3.x,List,在Python 3中,我有两个长度相同的列表,如下所示: A = [[0], [0, 1], [0, 1, 2], [0, 1], [0, 1, 2, 3]] W = [[2, 2], [1, 2, 3], [2, 2, 2, 3], [1, 3, 4, 4], [1, 1, 3, 4]] A的元素是W元素的索引。我想删除给定A的W元素。因此,在这个例子中,我想删除W[0][0],W[1][0],W[1][1],W[2][0],W[2][1],W[2][2],等等 我所做的是: for t i

在Python 3中,我有两个长度相同的列表,如下所示:

A = [[0], [0, 1], [0, 1, 2], [0, 1], [0, 1, 2, 3]]
W = [[2, 2], [1, 2, 3], [2, 2, 2, 3], [1, 3, 4, 4], [1, 1, 3, 4]]
A
的元素是
W
元素的索引。我想删除给定
A
W
元素。因此,在这个例子中,我想删除
W[0][0]
W[1][0]
W[1][1]
W[2][0]
W[2][1]
W[2][2]
,等等

我所做的是:

for t in range(len(A)):
    del W[t][A[t]]

但这会产生以下错误:
TypeError:list索引必须是整数或片,而不是list

一种简单的方法是使用两个嵌套循环。正如您现在可能已经注意到的,您需要两个索引号—一个用于A中的列表,另一个用于此列表的元素号。这里有一种解决问题的方法:

A = [[0], [0, 1], [0, 1, 2], [0, 1], [0, 1, 2, 3]]
W = [[2, 2], [1, 2, 3], [2, 2, 2, 3], [1, 3, 4, 4], [1, 1, 3, 4]]

#cycle through list A and keep track of the list number i
for i, a_list in enumerate(A):
    #retrieve index from each list in A, start with the highest index to avoid index problems
    for j in sorted(a_list, reverse = True):
        #delete the element j in list i of W
        del W[i][j]

print(W)
#output
#[[2], [3], [3], [4, 4], []]

numpy
数组不同,您不能使用列表为列表编制索引。但您可以使用列表理解来完成此任务:

A = [[0], [0, 1], [0, 1, 2], [0, 1], [0, 1, 2, 3]]
W = [[2, 2], [1, 2, 3], [2, 2, 2, 3], [1, 3, 4, 4], [1, 1, 3, 4]]

res = [[j for i, j in enumerate(w) if i not in a] for a, w in zip(A, W)]

print(res)

[[2], [3], [3], [4, 4], []]

或者,如果您乐于使用第三方库,
numpy
语法更简单:

import numpy as np

res = [np.delete(i, j).tolist() for i, j in zip(W, A)]

您是否已在此循环中打印出
A[t]
?你的错误(以及如何处理这个问题)应该变得显而易见。它打印出
[0][0,1][0,1,2][0,1][0,1,1,2,3]
,问题在哪里?我理解错误,但无法修复。它们是列表。您必须从每个列表中检索每个整数,并从相应的W列表中删除元素。该功能使这两项任务更容易同步