简体   繁体   English

检查列表的元素是否可以被另一个列表的所有元素整除

[英]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.

相关问题 检查列表中的所有元素是否可被给定整数整除 - Check if all the elements in that list are divisible by some given integer or not 检查一个列表的每个元素是否是另一个列表的所有元素的倍数 - Check if each element of one list is a multiple of all the elements of another list 检查列表元素是否存在于另一个列表的元素中 - check if element of list is present in elements of another list 查找整数 i 是否可以被列表中的所有元素整除 - find if integer i is divisible by all elements in a list 列表(可能)可以被另一个整除吗? - Is a list (potentially) divisible by another? 如何检查元组或列表中的所有元素是否在另一个中? - How to check if all elements in a tuple or list are in another? 如何检查数字是否可以被列表中的元素之一整除(Python)? - How can I check if a number is divisible by one of the elements in a list (Python)? 在另一个列表中的列表中搜索元素并检查每个元素是否存在 - Search elements in a list in another list and check each element exist or not 检查列表的所有元素是否都在一个大的单个元素列表中 - Check if all elements of a list are in a big single element list 检查列表中的数字是否可被另一个数字整除的最有效方法 - Most efficient way to check if numbers in a list is divisible by another number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM