python删除基于其他列表的列表索引

2024-04-19 08:41:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两份清单,详情如下:

a = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
remove_a_index = [[0], [0, 2, 3], [1]]

remove_a_index中删除基于数字的基的列表索引的最佳解决方案是什么?例如,对于[0],我需要删除数字0


Tags: 列表index数字解决方案remove
3条回答

如果我正确理解了这个问题,这应该是可行的:

for i, to_remove in enumerate(remove_a_index):
    for j in reversed(to_remove):
        del a[i][j]

您可以使用嵌套的列表理解表达式,使用^{}^{}过滤内容,如下所示:

>>> a = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
>>> remove_a_index = [[0], [0, 2, 3], [1]]

>>> a = [[j for i, j  in enumerate(x) if i not in y] for x, y in zip(a, remove_a_index)]
# where new value of `a` will be:
# [[1, 1, 2], [5], [2, 3, 3]]

根据您想要的结果,如果您只想从a列表中删除零,那么您不需要中间的remove_a_index列表。您可以使用列表理解表达式跳过新列表中的零,如下所示:

>>> a = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]

>>> [[j for j in i if j!=0] for i in a]
[[1, 1, 2], [5], [2, 3, 3]]

Python有一个名为List Comprehensions的语言特性,非常适合使这类事情变得非常简单。下面的语句执行您想要的操作,并将结果存储在l3中:

As an example, if I have l1 = [1,2,6,8] and l2 = [2,3,5,8], l1 - l2 should return [1,6]

l3 = [x for x in l1 if x not in l2]
l3 will contain [1, 6].

希望这有帮助!你知道吗

相关问题 更多 >