我正在尝试定义一种方法来检查列表中的每个元素是否都是参数的一个因素。
这是我所拥有的:
def factorall(x):
if all(x % num for num in nums) == 0:
return True
else:
return False
(在这种情况下,nums 是从 1 到 10 的整数列表)
但是,这对任何数字都返回 true。我假设发生这种情况是因为它只检查 1 然后返回 True,但 all() 不应该在返回 True 之前检查列表中的每个元素吗?
我对 all() 有点陌生,所以我可能实现不正确。有人可以指出我正确的方向吗?
谢谢!
请您参考如下方法:
你应该使用 not any 而不是 all
def factorall(x):
return not any(x%num for num in nums) #if any of these is a value other than 0
或者如果你想要它就像你现在拥有的那样
def factorall(x):
return all(x%num==0 for num in nums)
