[英]Iterate Function through List
I have a function prime(x) that returns True if x is prime and False if x is false. 我有一个函数prime(x),如果x是素数则返回True,如果x是假,则返回False。
Is there an efficient way to iterate through a list and if all the members satisfy the function, return True, and otherwise return false? 是否有一种有效的方法来遍历列表,如果所有成员都满足该函数,则返回True,否则返回false?
For the prime example, I wrote: 对于最好的例子,我写道:
def primecheck(x):
for index in xrange(0,len(x)):
if prime(x[index])==False:
return False
break
return True
but I imagine that this is inefficient and there must be a much better way of doing it. 但我认为这是低效的,必须有一个更好的方法来做到这一点。
Is there a standard method for iterating a generic function (where I define a generic function as something that evaluates an integer or string to be True or False) through a list without having to do something like the above each time? 有没有一种标准方法可以通过列表迭代泛型函数(我将泛型函数定义为评估整数或字符串为True或False的东西),而不必每次都执行上述操作? Or even if there isn't a standard method, is there a more efficient method than running through the index of the list?
或者即使没有标准方法,有没有比运行列表索引更有效的方法?
Yep! 是的! Use
all
in tandem with a generator expression: all
与生成器表达式一起使用:
def primecheck_all(x):
return all(prime(n) for n in x)
That's about the same as doing the following: 这与执行以下操作大致相同:
def primecheck_longway(x):
for n in x:
if not prime(n):
return False
return True
Doing some timing, it seems that primecheck_longway
is actually faster, though, although primecheck_all
is much easier to read. 做一些计时,看来
primecheck_longway
实际上更快,尽管primecheck_all
更容易阅读。 primecheck_xrange
(your version) is slowest: primecheck_xrange
(您的版本)最慢:
>>> def prime(n):
#simple function so all timing goes to how the list check is done
return n % 2 == 0
>>> l = range(100)
>>> timeit.timeit(lambda: primecheck_all(l))
1.4247075990295475
>>> timeit.timeit(lambda: primecheck_longway(l))
0.6282418298159413
>>> timeit.timeit(lambda: primecheck_xrange(l))
1.161489160644436
>>> l = range(2,100,2)
>>> timeit.timeit(lambda: primecheck_all(l))
10.058764784981875
>>> timeit.timeit(lambda: primecheck_longway(l))
7.728265179204939
>>> timeit.timeit(lambda: primecheck_xrange(l))
10.481824344034152
This is likely due to not having to have the overhead of the generator. 这可能是由于不必具有发电机的开销。 That's a 2.3 second difference for one million iterations, to put it in perspective.
对于100万次迭代,这是一个2.3秒的差异,以便对其进行透视。
Your code is really similar to how all
works anyway. 无论如何,你的代码与
all
代码的代码非常相似。 A few changes to your code gives this 对代码进行一些更改即可
def primecheck(x):
for i in x:
if not prime(i):
return False
return True
All I changed was to loop over x
instead of the range
, and to remove the unnecessary break
. 我改变的只是循环
x
而不是range
,并删除不必要的break
。
Using all
is neater, but the long hand version works for very very old versions of Python (<2.5) too. 使用
all
更整洁,但长版本适用于非常旧版本的Python(<2.5)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.