了解 Python 中的 any()-all()

Understanding any()-all() in Python

我对 Python 有点经验,但是,仍然不明白如何使用 all()any()。我正在尝试解决问题;

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

我的算法最初是这样的;

tp = (1,2,3,4,5,6,7,8,9,10,
      11,12,13,14,15,16,17,
      18,19,20) #I used tuple so I thought process may faster than list

for x in range(100,100000,2):
    for t in tp:
        if x%t==0:
            print(x)

然而,在我 运行 脚本之前,我意识到我的算法是错误的,因为数字可能被元组中的 all 数字整除。然后我记得 all() 功能,我试着改变我的代码;

if all(x%t==0):
    print(x)

但是我遇到了 TypeError: 'bool' object is not iterable 错误。可能我以前没用过all()any(),只是看了一些例子没看懂。谁能给我解释清楚?那我就可以解决这个问题了

all()any() 需要传递给它们的可迭代参数。

  • all() returns true 当且仅当 iterable 中的所有值都是 truthy.
  • any() returns 如果可迭代对象中的任何一个值是 truthy.
  • 则为真

对于您的特定问题,您最好改用 filter,因为它可以同时支持可迭代对象和函数。

由于 all() 函数接受一个可迭代对象作为其参数,因此您可以在其中传递一个生成器,就像您在 python 3 中一样,您可以使用 range(1,20) 即 return生成器而不是元组:

>>> for x in range(100,100000,2):
...     if all(x%t==0 for t in range(1,21)):
...        print (x)
... 
>>>

any()all() 使用列表,而不是方程式。虽然这些概念来自数学,但这些函数对值列表进行操作。也许你想要:

for x in range(100,10000,2):
    if all([x%t==0 for t in tp]):
        print(x)