gpt4 book ai didi

python删除基于另一个列表的列表索引

转载 作者:行者123 更新时间:2023-11-28 22:27:20 25 4
gpt4 key购买 nike

我有 2 个列表,详情如下:

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

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

最佳答案

您可以使用 zip() 来使用嵌套的列表理解 表达式和 enumerate()将内容过滤为:

>>> 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删除基于另一个列表的列表索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com