我有两个列表:
s = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
a = [2,6]
我想打印所有可以被a [0]和a [1]整除的s列表的所有数字。
在这种情况下,我会简单地做:
for num in s:
if num % a[0] == 0 and num % a[1] == 0:
print(num)
但是假设我不知道列表有多长。我该怎么办?
我已经设法弄清楚了一段时间,但是我被困住了。
答案 0 :(得分:1)
您可以将all
函数与这样的生成器表达式一起使用:
if all(num % i == 0 for i in a):
答案 1 :(得分:1)
您可以首先计算a
中的least common multiple:
from math import gcd
a = [2, 6]
s = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
lcm = a[0] * a[1] // gcd(a[0], a[1])
print(list(x for x in s if x % lcm == 0)
# [6, 12, 18, 24]
如果您的a
长于2个元素,这可能会更有效率。
为了获得元素列表的LCM,可以使用如下定义的lcm_lst
:
from math import gcd
def lcm(a, b):
return a * b // gcd(a, b)
def lcm_lst(a):
l = a[0]
for x in a[1:]:
l = lcm(l, x)
return l
答案 2 :(得分:0)
您可以将嵌套list-comp与all
一起使用,例如:
s = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
a = [2,6]
result = [x for x in s if all(x % y == 0 for y in a)]
给你:
[6, 12, 18, 24]