输入:
ls = ['hi', 'bye', 'cya', 'hello', 'nope']
ls_popped = []
i = 0
while i < 3:
ls_popped.append(ls.pop(i))
i += 1
print(ls)
print(ls_popped)
输出:
['bye', 'hello']
['hi', 'bye', 'nope']
预期输出:
['hello', 'nope']
['hi', 'bye', 'cya']
我相信pop函数会弹出并返回索引i处的元素,所以它应该从i=0弹出到2,并将这些元素返回到新列表中。我不知道为什么这没有如预期的那样起作用。
让我们追踪一下。在你的项目开始时,我们有
ls = ['hi', 'bye', 'cya', 'hello', 'nope']
ls_popped = []
i = 0
现在我们运行一次循环。我们在位置0弹出元素,并将其附加到ls_popped
。
ls = ['bye', 'cya', 'hello', 'nope']
ls_popped = ['hi']
i = 1
太棒了!现在循环变量是1
。所以我们把它放在1号位置。请注意,这不是bye
:bye
现在为0,而cya
为1。
ls = ['bye', 'hello', 'nope']
ls_popped = ['hi', 'cya']
i = 2
现在i
是2,所以我们看位置2,它包含nope
。
ls = ['bye', 'hello']
ls_popped = ['hi', 'cya', 'nope']
i = 3
现在i
是3,所以循环退出,我们继续,打印结果
它有助于直观地查看您的列表:
'hi', 'bye', 'cya', 'hello', 'nope'
-----------------------------------
0 1 2 3 4
我们从0
的while
循环开始,提取第一个元素并放入ls_popped
。当您提取第一个元素时,ls
中的其余元素会发生偏移,因此在视觉上看起来像:
'bye', 'cya', 'hello', 'nope'
-----------------------------
0 1 2 3
现在i
增加到1
,因此现在提取cya
并将其附加到ls_popped
中。
ls
:
'bye', 'hello', 'nope'
----------------------
0 1 2
现在i
是2
,所以我们提取nope
并将其附加到ls_popped
。
在部分中打破列表的更好方法是通过切片,而不是通过循环和pop
:
ls = ['hi', 'bye', 'cya', 'hello', 'nope']
idx_cut = 3
ls_popped = ls[:idx_cut]
ls = ls[idx_cut:]
print(ls)
print(ls_popped)
# ['hello', 'nope']
# ['hi', 'bye', 'cya']
另请参阅:
- 了解切片
- Python教程:列表