从列表中删除一组位置

2024-04-27 04:15:35 发布

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

尽管使用for循环应该很容易做到这一点,但我想知道是否有一种简洁的方法可以从Python列表中删除一组位置。例如:

l = ["A","B","C","D","E","F","G"]
pos = [4,6]
# Is there something close to
l.remove(pos)

最好的


Tags: to方法pos列表forcloseissomething
1条回答
网友
1楼 · 发布于 2024-04-27 04:15:35

del是您想要的,如果您有连续的索引

根据文件:

There is a way to remove an item from a list given its index instead of its value: the del statement

否则,您可以通过过滤掉您不感兴趣的索引来生成一个新列表

result = [x for i, x in enumerate(l) if i not in pos]

相关问题 更多 >