pop()函数不能完全弹出列表中位数

时间:2019-03-05 04:45:37

标签: python python-3.x

问题描述:

un_confirmusers = ['A','B','C','D','E']
confirmusers = []
for un_confirmuser in un_confirmusers:
    current_user = un_confirmusers.pop()
    print("The current USER is: " + current_user.title())
    confirmusers.append(current_user)
print(confirmusers)
print(un_confirmusers)

编译结果:

The current USER is: E
The current USER is: D
The current USER is: C
['E', 'D', 'C']
['A', 'B']

我不知道pop()不能完全弹出列表中位数。 谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用for-loop

代替使用while-loop

例如:

un_confirmusers = ['A','B','C','D','E']
confirmusers = []
while un_confirmusers:                      #!Update.
    current_user = un_confirmusers.pop()
    print("The current USER is: " + current_user.title())
    confirmusers.append(current_user)
print(confirmusers)
print(un_confirmusers)

输出:

The current USER is: E
The current USER is: D
The current USER is: C
The current USER is: B
The current USER is: A
['E', 'D', 'C', 'B', 'A']
[]

注意:在对象上进行迭代时删除元素不是一个好习惯。

答案 1 :(得分:1)

您要对要迭代的列表进行变异,因此跟踪3次迭代的内部索引发现自己大于列表的长度,并在3次迭代后结束了循环。

您应该遍历un_confirmusers的副本,改为:

for un_confirmuser in un_confirmusers:

收件人:

for un_confirmuser in un_confirmusers[:]:

更改后,您的代码输出:

The current USER is: E
The current USER is: D
The current USER is: C
The current USER is: B
The current USER is: A
['E', 'D', 'C', 'B', 'A']
[]