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

标签 python python-3.x list for-loop

最近我了解了列表和 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.")

python 3.6 的输出给了我这个:

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
j
i
h
g
f
job done.

如您所见,它确实有效,但只有一半?

我期待:

j
i
h
g
f
e
d
c
job done

我的意思是,如果它返回一些错误,我会更舒服,这意味着代码不正确。但为什么它有效,但没有完全通过?

最佳答案

您在遍历列表的同时改变了列表。

您可以使用 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')

输出:

j
i
h
g
f
e
d
c
job done

A more efficient way would be to determine the index of the first instance of the sentinel character, and remove it and the rest of the list (although the characters are not printed as they are removed):

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

关于Python "for in"循环打印列表中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46086441/

相关文章:

python 3 : hook list & dict changes

python - 在 python 中处理长整数除法

python - 按键过滤字符串列表

python - 如何使用pid获取进程状态?

python - 自动生成 tor 导出节点列表

Python 时间序列预测(销量)

python - 如何在 tensorflow 中使用 QueueRunner 将动态创建的输入图像添加到 RandomShuffleQueue

python-3.x - 为什么我不能在 pydantic 中创建独立的 HttpURL 对象?

python-3.x - 在Python中获取维基百科的项目列表

Python 在列表中添加数字