我希望能够在元素小于或等于某个限制时迭代列表。我自己做了一个函数来产生我想要的结果,但我想知道是否有一个函数可以为我做这个,或者结果是否可以用列表理解之类的东西重现,所以我不必单独做一个函数调用?基本上,我想知道是否有更短/更快的方法来像这样进行迭代,因为我需要在多个 python 文件中使用它并进行大型迭代。
我查看了 python 2.7 的 itertools 文档 https://docs.python.org/2/library/itertools.html我认为它会有我正在寻找的东西(它可能有但我错过了它,因为我不理解 itertools 中的几个函数)。
这是我所拥有的和我想要的结果的示例:
def iterList(iList, limit):
index = 0
while index < len(iList) and iList[index] <= limit:
yield iList[index]
index += 1
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
smallPrimes = list()
for p in iterList(primes, 19):
smallPrimes.append(p)
print smallPrimes
# now smallPrimes == [2, 3, 5, 7, 11, 13, 17, 19]
请您参考如下方法:
您使用 itertools.takewhile() :
from itertools import takewhile
for p in takewhile(lambda i: i < 20, primes):
takewhile 迭代直到谓词不再为真。
演示:
>>> from itertools import takewhile
>>> primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> for p in takewhile(lambda i: i < 20, primes):
... print p
...
2
3
5
7
11
13
17
19
