python - 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
解决方案
作为一般规则,我会避免修改我正在迭代的对象。这可能会导致非常奇怪的行为。
您是否考虑过具有列表理解的解决方案?在我看来,在这种情况下,它是最 Pythonic 的实现。
lst = ['XDA-OT', 'hi', 'loc', 'yeah']
lst = [itm for itm in lst if len(itm) <= 3]
推荐阅读
- javascript - 获取 WebUSB API 中可用的 USB 设备列表
- javascript - 有没有办法让窗户自行关闭?
- python - 带有自定义主循环的 python socketio 服务器
- javascript - 持久化有状态的 React 组件
- pdf - SwiftUI 使用 PDFKit 将 PDF 保存到远程文件
- python - PsyNet 实验抛出与 requirements.txt 相关的错误
- python - Docker django.db.utils.OperationalError:无法将主机名“db”转换为地址:名称解析暂时失败
- javascript - 获取前 N 个素数的总和 javascript
- node.js - 节点异或两个大小不等的数组 - 未定义异或的行为
- html - 在引导网格列上添加背景颜色,防止着色默认网格列填充