python for in循环列表,Python“for”in“循环打印列表中的最后一个项目

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值