Python“for”in“循环打印列表中的最后一个项目 [英] Python "for in" loop to print the last item in the list

查看:837
本文介绍了Python“for”in“循环打印列表中的最后一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

b
$ b

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



<代码是:

$ $ $ $ $ $ c $ list_A = ['a','b','c','d',' (list_A.pop())$ b(

$ b)给我在list_A:
print(list_A.pop())
if'c'not in list_A:
break

print(job done。)

python 3.6的输出给了我:
$ b

  / Library / Frameworks / Python。 framework / Versions / 3.6 / bin / python3.6 
j
i
h
g
f
完成了工作。

正如你所看到的,它实际上是工作的,但是它的一半呢? b
$ b

我期待:

  j 
i
h
g
f
e
d
c
完成工作



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

解决方案

你正在改变列表,同时迭代它。



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

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

而list_A中的'c':
print(list_A.pop())

print('job done')

输出:

 j 
i
h
g
f
e
d
c
完成工作

更有效的方法是确定哨兵字符的第一个实例的索引,并删除它和列表的其余部分(尽管字符在被删除时不会被打印) p>

  try:
pos = list_A.index('c')
list_A [:] = list_A [ [b]
#del list_A [pos:]#由@ShadowRanger建议的更有效的替代方法
除了ValueError以外:
传递


Lately I learned about lists and for loops, as well as the command .pop() that indicates and removes the last item in a list.

So I tried to write a code to remove the last items in a list one by one, until it remains with only one item.

The code is:

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.")

The output of python 3.6 gives me this:

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

As you can see, it actually worked, but for a half of it?

I was expecting:

j
i
h
g
f
e
d
c
job done

I mean, I will be more comfortable if it returns some error, that means the code is not right. But why did it work, but not a full way through?

解决方案

You are mutating the list whilst iterating over it.

You can use a while loop to do this:

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

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

print('job done')

Output:

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“循环打印列表中的最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆