为什么pop函数没有弹出正确的索引

  • 本文关键字:索引 pop 函数 python
  • 更新时间 :
  • 英文 :


输入:

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

我们从0while循环开始,提取第一个元素并放入ls_popped。当您提取第一个元素时,ls中的其余元素会发生偏移,因此在视觉上看起来像:

'bye', 'cya', 'hello', 'nope'
-----------------------------
0       1      2       3

现在i增加到1,因此现在提取cya并将其附加到ls_popped中。

ls:

'bye', 'hello', 'nope'
----------------------
0       1        2       

现在i2,所以我们提取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教程:列表

最新更新