如何检查列表中每个项目的模数除法的结果,并检查每个数字是否满足条件

时间:2022-03-11 14:30:25

I realize my question title might be a little confusing so I'll give context. I have code where it first generates a random number, then it creates a list based on that random number where the range is (random number, random number + 15).

我意识到我的问题标题可能有点令人困惑所以我会给出背景。我有代码,它首先生成一个随机数,然后根据该范围的随机数创建一个列表(随机数,随机数+15)。

What I want to do is create an if statement where if every item within that range can not be divided by an inputted number then it would return as True and then carry out whatever is supposed to happen then. (I'm using Python 3 for this)

我想要做的是创建一个if语句,如果该范围内的每个项目都不能被输入的数字除,那么它将返回True,然后执行应该发生的任何事情。 (我正在使用Python 3)

For example, if my list is [8, 9, 10, 11, 12] and my inputted number is 5, then it should check if every number in there doesn't have a remainder of 0 (in this case, the list wouldn't satisfy this condition as 10 % 5 == 0). Because this isn't the case here, the code would then look to the else statement.

例如,如果我的列表是[8,9,10,11,12]并且我输入的数字是5,那么它应该检查那里的每个数字是否没有余数0(在这种情况下,列表不会不满足这个条件为10%5 == 0)。因为这不是这种情况,所以代码将查找else语句。

I had a few ideas but none of them are working. I'll list out the two I remember off of the top of my head.

我有一些想法,但没有一个是有效的。我会列出我头脑中记得的两个。

if all(x % distance == 0 for x in jagX):

and

if (all(jagX) % distance == 0):

For some reason, these always returned a true even though I purposefully used inputs that should cause these if statements to be false every time (I would make distance be 2 as a test to see if this recognizes when the statement is false)

出于某种原因,这些总是返回true,即使我故意使用的输入应该导致这些if语句每次都是假的(我会将距离设为2作为测试,以查看当语句为false时是否识别)

1 个解决方案

#1


0  

If you use any() with a generator expression, this can be built like:

如果你将any()与生成器表达式一起使用,可以构建如下:

Code:

def test_zero_modulo_in_list(list_to_test, modulo):
    return not any(i % modulo == 0 for i in list_to_test)

Test Code:

a_list = [8, 9, 10, 11, 12]

print(test_zero_modulo_in_list(a_list, 5))
print(test_zero_modulo_in_list(a_list, 13))

Results:

False
True

#1


0  

If you use any() with a generator expression, this can be built like:

如果你将any()与生成器表达式一起使用,可以构建如下:

Code:

def test_zero_modulo_in_list(list_to_test, modulo):
    return not any(i % modulo == 0 for i in list_to_test)

Test Code:

a_list = [8, 9, 10, 11, 12]

print(test_zero_modulo_in_list(a_list, 5))
print(test_zero_modulo_in_list(a_list, 13))

Results:

False
True