python - 在 `any` 函数中找到失败的元素

标签 python

有没有办法知道哪个元素未通过任何内置函数?

我试图解决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/

相关文章:

python - 在 Python 中使用 igraph 创建网络的性能瓶颈

python - 在 Linux 上使用 headless Chrome 访问拒绝页面,而有头 Chrome 通过 Python 使用 Selenium 在 Windows 上运行

python - 为什么 for 中的逗号分隔迭代不像 zip 那样工作?

python - 当我们有一些未存储的字段时,如何使用 whoosh 模块更新索引文档?

python - ftplib 远程更改文件

python - 如何使用 Django Rest Framework 保存对象数组

Python 应用程序和 Python 解释器?

python - 是否有一个 numpy 函数返回给定大小的数组索引矩阵?

python - 如何使用请求库来网络抓取已抓取的链接列表

python - 如何将经度、纬度、高程转换为直角坐标?