python - 如何跳过 `for` 循环中的第一个元素?

标签 python for-loop iterator

在 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:]) 但这会生成一个副本并且不适用于所有序列、迭代器、集合等。

最佳答案

for i in list1[1:]: #Skip first element
    # Do What Ever you want

解释:

当你在 for 循环列表中使用 [1:] 时,它会跳过第一个元素并开始从第二个元素到最后一个元素的循环

关于python - 如何跳过 `for` 循环中的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20682273/

相关文章:

python - 如何从字符串末尾向后剥离模式或单词?

python - AppEngine python 线程能否比原始请求持续更长时间?

objective-c - 在没有副作用的情况下删除 for 循环中的项目?

optimization - F# "for loop"优化

Python:使用 py2app 在 MacOS 上制作一个独立的可执行文件

python - 在python中导入文件时地址已被使用

actionscript-3 - as3中的EventListener和for循环

c++ - 从双端队列中删除某个位置的对象

c++ - 如何访问/迭代 unordered_multimap 中的所有非唯一键?

c++ - 与容器无关的迭代器参数