python 中是否有一种健壮、通用的方法来跳过 for
循环中的第一个元素?
我能想到的唯一方法是手动编写一个特殊的生成器:
def skipFirst( it ):
it = iter(it) #identity for iterators
it.next()
for x in it:
yield x
并使用它例如:
for x in skipFirst(anIterable):
print repr(x)
喜欢:
doStuff( str(x) for x in skipFirst(anIterable) )
喜欢:
[ x for x in skipFirst(anIterable) if x is not None ]
我知道我们可以在列表上做切片 (x for x in aList[1:])
但这会生成一个副本并且不适用于所有序列、迭代器、集合等。
原文由 user2622016 发布,翻译遵循 CC BY-SA 4.0 许可协议
当只跳过 一项 时,我会使用
next()
函数:通过给它第二个参数,一个默认值,它也会吞下
StopIteration
异常。它不需要导入,可以简化混乱的for
循环设置,并且可以 在for
循环中使用以有条件地跳过项目。如果您希望 遍历
it
跳过第一项,那么itertools.islice()
是合适的: