有没有办法知道哪个元素未通过任何
内置函数?
我试图解决Euler 5我想找出我的乘积不能被整除的数字。使用 for 循环很容易弄清楚,但是使用 any
也可以吗?
from operator import mul
primes_under_20 = [2,3,5,7,11,13,17,19]
product = reduce(mul, primes_under_20, 1)
if any((product % i != 0 for i in range(1,21))):
print "not evenly divisible"
# how can I find out that 4 was the element that failed?
# must I use this for loop?
for i in range(1,21):
if product % i != 0:
print i # prints 4
break
我读到here any
相当于:
def any(iterable):
for element in iterable:
if element:
return True
return False
但这是否是确切的实现,或者是否存在隐藏的yield
,或者类似的东西可以帮助锁定元素?
最佳答案
有什么充分的理由使用any
吗?
如果您想要一行代码找出哪些数字不能被整除:
not_divisible = [i for i in range(1, 21) if product % i != 0]
if len(not_divisible) > 0:
print(not_divisible)
您无法真正使用 any
获得所有不可整除的数字,因为当它在可迭代中找到第一个 False
时,它就会停止
关于python - 在 `any` 函数中找到失败的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016216/