Python"for in"循环打印列表中的最后一项

Cod*_*755 4 python for-loop list python-3.x

最近我学习了列表和for循环,以及.pop()指示和删除列表中最后一项的命令.

所以我试着编写一个代码来逐个删除列表中的最后一项,直到它只剩下一个项目.

代码是:

list_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

for i in list_A:
    print(list_A.pop())
    if 'c' not in list_A:
        break

print("job done.")
Run Code Online (Sandbox Code Playgroud)

python 3.6的输出给了我:

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
j
i
h
g
f
job done.
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,它确实有效,但只有一半呢?

我在期待:

j
i
h
g
f
e
d
c
job done
Run Code Online (Sandbox Code Playgroud)

我的意思是,如果它返回一些错误,我会更舒服,这意味着代码不正确.但为什么它有效,但不是完整的方式?

mha*_*wke 5

你在迭代它时改变列表.

您可以使用while循环来执行此操作:

list_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

while 'c' in list_A:
    print(list_A.pop())

print('job done')
Run Code Online (Sandbox Code Playgroud)

输出:

j
i
h
g
f
e
d
c
job done

一种更有效的方法是确定sentinel字符的第一个实例的索引,并将其删除和列表的其余部分(尽管字符在删除时不会打印):

try:
    pos = list_A.index('c')
    list_A[:] = list_A[:pos]
    # del list_A[pos:]           # more efficient alternative suggested by @ShadowRanger
except ValueError as e:
    pass
Run Code Online (Sandbox Code Playgroud)