我想循环检查每个项目的列表与其后面的项目.
有没有办法可以循环使用除了最后一项使用x中的所有项目?如果可以的话,我宁愿不使用索引.
注意
freespace回答了我的实际问题,这就是我接受答案的原因,但是SilentGhost回答了我应该问的问题.
为混乱道歉.
fre*_*ace 281
for x in y[:-1]
Run Code Online (Sandbox Code Playgroud)
如果y
是发电机,那么上述将无效.
Sil*_*ost 46
将序列项与以下内容进行比较的最简单方法:
for i, j in zip(a, a[1:]):
# compare i (the current) to j (the following)
Run Code Online (Sandbox Code Playgroud)
Ant*_*sma 19
如果要获得序列对中的所有元素,请使用此方法(成对函数来自itertools模块中的示例).
from itertools import tee, izip, chain
def pairwise(seq):
a,b = tee(seq)
b.next()
return izip(a,b)
for current_item, next_item in pairwise(y):
if compare(current_item, next_item):
# do what you have to do
Run Code Online (Sandbox Code Playgroud)
如果需要将最后一个值与某个特殊值进行比较,请将该值链接到结尾
for current, next_item in pairwise(chain(y, [None])):
Run Code Online (Sandbox Code Playgroud)
如果你的意思是比较第n项和列表中的第n + 1项,你也可以这样做
>>> for i in range(len(list[:-1])):
... print list[i]>list[i+1]
Run Code Online (Sandbox Code Playgroud)
请注意,那里没有硬编码.除非你有其他想法,否则这应该没问题.
归档时间: |
|
查看次数: |
147575 次 |
最近记录: |