gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:33:46 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com