如何遍历除列表最后一项之外的所有内容? [英] How to loop through all but the last item of a list?
本文介绍了如何遍历除列表最后一项之外的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想遍历一个列表,根据它后面的项目检查每个项目.
I would like to loop through a list checking each item against the one following it.
有什么方法可以循环使用 for x in y 除了最后一个项目之外的所有项目?如果可以,我更愿意不使用索引.
Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.
注意
freespace 回答了我的实际问题,这就是为什么我接受了答案,但 SilentGhost 回答了我应该问的问题.
freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.
对于造成的混乱深表歉意.
Apologies for the confusion.
推荐答案
for x in y[:-1]
如果 y
是一个生成器,那么上面的将不起作用.
If y
is a generator, then the above will not work.
这篇关于如何遍历除列表最后一项之外的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文