python - 按索引从另一个整数列表中删除列表中的元素

标签 python list

所以我有两个列表:

num = [
    3, 22, 23, 25, 28, 29, 56, 57, 67, 68, 73, 78, 79, 82, 83, 89, 90, 91,
    92, 98, 99, 108, 126, 127, 128, 131, 132, 133
]
details = [
    'num=10,time=088', 'num=10,time=084', 'num=10,time=080', 'num=10,time=076',
    'num=10,time=072', 'num=10,time=068', 'num=10,time=064', 'num=10,time=060',
    'num=10,time=056', 'num=10,time=052', 'num=10,time=048', 'num=10,time=044',
    .
    .
    .
    .
    'num=07,time=280', 'num=07,time=276', 'num=05,time=508', 'num=05,time=504',
    'num=05,time=500', 'num=05,time=496'
]

num 有 28 个元素,details 有 134 个元素。我想根据 num 中的值按索引删除 details 中的元素。例如,索引为 3、22、23、25、28 的元素(这些是 num 列表中的数字)应该从 details 中删除。

当我按照描述使用 .pop()here它给我一个错误说:

AttributeError: 'str' object has no attribute 'pop'

类似地,当我使用 del details[] 时,它给我一个错误提示:

IndexError: list assignment index out of range

这是我的代码:

for an in details:
    an.pop(num)

最佳答案

这应该做你想做的(从 details 中删除由 num 中的值索引的每个元素):

for i in reversed(num):
    del details[i]

它向后遍历列表,以便 future 要删除的内容的索引不会改变(否则你会删除 3,然后以前索引为 22 的元素将是 21)——这可能是你的来源索引错误。

关于python - 按索引从另一个整数列表中删除列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50180289/

相关文章:

python - 如何访问列表列表中的条目并打印该列表中的其他条目

python - 如何通过遍历具有相同键多个值的列表来创建字典?

python - 日期滚动总和指数

Python 访问错误的 key

Python将顺序值数组添加到dict

java - Java中.add()返回一个 boolean 值,如何以列表形式返回

r - 从没有循环的嵌套列表中提取元素

python - cv2.error : OpenCV(4. 5.2) .error : (-215:Assertion failed) ! _src.empty() 函数 'cv::cvtColor'

python - 如何从 Docker 文件中的自定义文件 channel 安装 conda 包?

Python错误: TypeError: unsupported operand type(s) for +: 'int' and 'str'