首页 > 解决方案 > del(item) 与 python 列表中的 list.remove(item) 有何不同

问题描述

我想从长度大于 3 的列表中删除单词。我使用了 del (item) 但它没有用。这是代码:

lst=['XDA-OT','hi','loc','yeah']
for i in lst:
    if len(i)>3:
        del i

和输出:

lst
['XDA-OT', 'hi', 'loc', 'yeah']

现在我使用remove()了 Python List 函数,得到了想要的结果。

这是相同的代码:

lst=['XDA-OT','hi','loc','yeah']
for i in lst:
    if len(i)>3:
        lst.remove(i)

输出:

print(lst)
['hi', 'loc']

我也怀疑使用列表索引从列表中删除元素,但不明白如何提出问题。

每当我使用索引删除元素时,我都会得到 IndexError。代码:

lst=['XDA-OT','hi','loc','yeah']
for i in range(len(lst)):
    if len(lst[i])>3:
        del lst[i]

输出错误:

IndexError                                
<ipython-input-35-617282928840> in <module>()
      1 for i in range(len(lst)):
----> 2     if len(lst[i])>3:
      3         del lst[i]

IndexError: list index out of range

同样使用 remove() 函数。代码:

lst=['XDA-OT','hi','loc','yeah']
for i in range(len(lst)):
    if len(lst[i])>3:
        lst.remove(lst[i])

输出错误:

IndexError                                
<ipython-input-39-1d824ca5b061> in <module>()
      1 for i in range(len(lst)):
----> 2     if len(lst[i])>3:
      3         lst.remove(lst[i])

IndexError: list index out of range

标签: python

解决方案


作为一般规则,我会避免修改我正在迭代的对象。这可能会导致非常奇怪的行为。

您是否考虑过具有列表理解的解决方案?在我看来,在这种情况下,它是最 Pythonic 的实现。

lst = ['XDA-OT', 'hi', 'loc', 'yeah']
lst = [itm for itm in lst if len(itm) <= 3]

推荐阅读