当元素<=限制时,是否有一个内置函数(或其他方法)来迭代列表?

2024-04-20 16:09:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够在元素小于或等于某个限制时遍历列表。我自己做了一个函数来产生我想要的结果,但是我想知道是否有一个函数可以为我这样做,或者是否可以用类似列表理解的方法来重现结果,这样我就不必进行单独的函数调用了?基本上,我想知道是否有这样一种更短/更快的迭代方式,因为我需要在多个python文件和大型迭代中使用它。你知道吗

我已经浏览了python2.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]

Tags: 文件方法函数文档元素列表index方式
2条回答

使用^{}

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

您正在搜索takewhile: 它生成一个迭代器,只要谓词为真,它就生成元素。你知道吗

takewhile(lambda x: x<5, [1,4,6,4,1]) #  > 1 4

相关问题 更多 >