【发布时间】:2021-07-19 03:30:08
【问题描述】:
我目前正在学习 Python,但我很难理解切片 [:] 在下面显示的 for 循环中的作用。
我没有找到关于[:] 语法的任何问题,所以我发布了一个问题。
我知道写 namesList[2:] 会从索引 2 中分割列表:['three', 'four', 'five']
并且namesList[:2] 将分割列表直到索引 1:['one', 'two']。
- 如果在 for 循环中我只放了
for nm in namesList:,它就会卡在一个无限循环中,不断地在索引 0 中插入“四”。为什么卡住了?
- 根据我在调试中看到的情况,在带有
namesList[:]的for 循环中,它从停止的地方继续。但是为什么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
【问题讨论】:
-
这能回答你的问题吗? Understanding slice notation
-
@BillLynch,谢谢第一个链接帮助我理解stackoverflow.com/questions/4081561/…
标签: python