[英]Check if element of a list is divisible by all elements of another list
I have two lists:我有两个清单:
s = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
a = [2,6]
I want to print all numbers of s list that are both divisible by a[0] and a[1].我想打印所有可以被 a[0] 和 a[1] 整除的 s 列表。
In a case like this I would simply do:在这种情况下,我会简单地做:
for num in s:
if num % a[0] == 0 and num % a[1] == 0:
print(num)
But let's assume I don't know how long the list is.但是让我们假设我不知道列表有多长。 How can I get it right?我怎样才能正确?
I've tried to figure this out for some time now, but I am stuck.我已经尝试解决这个问题一段时间了,但我被卡住了。
You can use the all
function with a generator expression like this:您可以将all
function 与生成器表达式一起使用,如下所示:
if all(num % i == 0 for i in a):
You can use a nested list-comp with all
, eg:您可以将嵌套列表组合与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)]
Gives you:给你:
[6, 12, 18, 24]
you could calculate the least common multiple of a
first:您可以计算第a
的最小公倍数:
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]
this may be more efficient if your a
is longer than just 2 elements.如果您a
长于 2 个元素,这可能会更有效。
in order to get the LCM of a list of elements you could use lcm_lst
as defined below:为了获得元素列表的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.