python - [ :] mean in the context of "for nm in namesList[:]:" 是什么意思

标签 python

我目前正在学习 Python,我很难理解切片 [:] 在如下所示的 for 循环中的作用。
我没有找到任何关于[:]的问题语法,所以我发布一个问题。

我明白写namesList[2:]将从索引 2 开始对列表进行切片:['three', 'four', 'five']
namesList[:2]将对列表进行切片,直到索引 1:['one', 'two']

  1. 如果在 for 循环中我只输入 for nm in namesList:它陷入了无限循环,不断向索引 0 插入“4”。为什么会陷入困境?
  2. 从我在调试中看到的情况来看,在 for 循环中 namesList[:] ,它从停止的地方继续。但为什么namesList:不继续,并且 namesList[:]做? [:]怎么样工作,语法是什么意思?

names = "one two three four five"
namesList = names.split()    
for nm in namesList[:]:
    if nm[0] == "f":
        namesList.insert(0, nm)
print(namesList)

# Output:
['five', 'four', 'one', 'two', 'three', 'four', 'five']

names = "one two three four five"
namesList = names.split()    
for nm in namesList:
    if nm[0] == "f":
        namesList.insert(0, nm)
print(namesList)

# Infinite loop

最佳答案

这是一个很好的(如果有点武断)示例,说明为什么在迭代列表(或其他数据结构)时不应修改列表(或其他数据结构)。

在第二个代码中,循环最终到达4,因此决定在列表的开头插入一些内容。

但这会将列表中的所有其他元素向前移动,循环不知道这一点,所以现在它再次看到四个。一次又一次……

切片的作用本质上是创建列表的副本。这样,循环只会在列表的原始部分上运行,从而保存修改该列表。

它复制列表的原因是一般 my_list[3:5] 左右会选择从第一个索引开始并运行到的元素(但不包括) 最后一个索引。如果省略第一个索引,则默认为 0,如果省略最后一个索引,则默认为最后一个元素,因此 [:] 只是表示“选择所有元素” ,从 0 到最后”。

关于python - [ :] mean in the context of "for nm in namesList[:]:" 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67255098/

相关文章:

python - 尽管每个循环只分配一次变量,但为什么变量会发生变化?

python - Pandas 数据框和附加对象转换为 JSON

python - 使用框架切换类的 Tkinter 按钮命令

python - BS HTML 解析 - & 在打印 URL 字符串时被忽略

python - 将 Python ctypes.Structure 转换为 str

python - 为什么 django-channels 无法连接到安全的 Websockets wss?

python - 根据 Pandas 中的单元格值索引列

BLE 的 python3 root 权限

python - 未合并的单元格 For 循环跳过单元格

python - 从父类访问命名元组中的派生属性