根据位置从Python列表中删除元素?

0 投票
2 回答
2949 浏览
提问于 2025-04-18 01:49

我在想,怎么才能根据位置来删除列表中的一部分呢?

rando = keywords[random.randint(0, 14)]
h = 0
for h in range(len(keywords)):
    if rando == keywords[h]:
        position = h

realAns = definitions[position]

我试过这个

rando.remove[h] 

但是好像没什么效果 :(

请问我该用什么代码才能正确地删除那个关键词(不是定义)呢?谢谢。

2 个回答

2

使用 del 命令,并指定你想删除的元素的 index(索引)。

>>> a=[i for i in range(1,11)]
>>>a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del a[0]
>>> a
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 

另外,你也可以使用 poppop 会返回被删除的元素

>>> a=[i for i in range(1,11)]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a.pop(1)
2
>>> a
[1, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 

如果你在 pop 中没有指定任何参数,它会删除最后一个项目。

>>> a=[i for i in range(1,11)]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a.pop()
10
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
1

如果你还想获取你正在移除的内容,可以这样做:

rando.pop(h)

否则你只需要这样做:

del rando[h]

撰写回答