python - 使用列表理解查找列表中的元素,其中另一个列表中的所有元素都是因子

标签 python list for-loop if-statement list-comprehension

我有一个数字列表,我从中提取了所有这些数字的公因数。例如,来自列表 b = [16, 32, 96] ,我制作了list_of_common_factors = [1, 8, 16, 2, 4] .

我有另一个整数列表,a我想从 list_of_common_factors 中提取数字其中 a 的所有元素是因素。所以如果a = [2, 4] , 那么我应该以 [4, 8, 16] 结尾,因为这些是 list_of_common_factors 中的数字其中2和4是因数。

但是,我正在努力弄清楚如何在列表理解中实现此步骤,即使是在伪代码中也是如此。它应该看起来像这样:[x for x in list_of_common_factors if all elements of a are factors of x] .我遇到麻烦的是 if 语句,因为我认为它应该包含一个 for 循环,但我想不出一种简洁的方式来编写它。

我已经设法做到了很长的路要走,使用嵌套的 for 循环,它看起来像这样:

between_two_lists = []
# Determine the factors in list_of_common_factors of which all elements of a are factors.
for factor in list_of_common_factors:
    # Check that all a[i] are factors of factor.
    """ Create a counter.
        For each factor, find whether a[i] is a factor of factor.
        Do this with a for loop up to len(a).
        If a[i] is a factor of factor, then increment the counter by 1.
        At the end of this for loop, check if the counter is equal to len(a).
        If they are equal to each other, then factor satisfies the problem requirements.
        Add factor to between_two_lists. """
    counter = 0
    for element in a:
        if factor % element == 0:
            counter += 1
    if counter == len(a):
        between_two_lists.append(factor)

between_two_lists是我试图通过将上述代码转换为列表理解来生成的列表。如果可能的话,我该怎么做?

最佳答案

这就是你要找的:

[x for x in list_of_common_factors if all(x % i==0 for i in a)]

关于python - 使用列表理解查找列表中的元素,其中另一个列表中的所有元素都是因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733940/

相关文章:

java - 打印多个数组项的单个计数值

python - 在python中手动安装nltk训练数据

python - Pandas、Concurrent.Futures 和 GIL

python - 如何从 Python 中的数据库中减去哈希密码

java - 使用迭代器迭代列表并比较连续元素

html - Firefox - 宽度 : 100% not working for list in a list (display: table;)

c# - C#'s most effective counterpart to Delphi' s TStringList 是什么?

javascript - 在 Javascript 的 for 循环中评估数组的所有值时出现问题

python - 按属性自定义排序

c++ - 固定限制的循环更快