[英]Check if all the elements in that list are divisible by some given integer or not
[英]Check if element of a list is divisible by all elements of another list
我有兩個清單:
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)
但是讓我們假設我不知道列表有多長。 我怎樣才能正確?
我已經嘗試解決這個問題一段時間了,但我被卡住了。
您可以將all
function 與生成器表達式一起使用,如下所示:
if all(num % i == 0 for i in a):
您可以將嵌套列表組合與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]
您可以計算第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]
如果您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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.