代码之家  ›  专栏  ›  技术社区  ›  AkThao

在列表中查找元素,其中其他列表中的所有元素都是因子,使用列表理解

  •  3
  • AkThao  · 技术社区  · 7 年前

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

    我还有一个整数列表, a 我想从中提取数字 list_of_common_factors 其中所有元素 这些都是因素。所以如果 a = [2, 4] [4, 8, 16] ,因为这些是 常见因素列表

    然而,我正在努力找出如何在列表理解中实现这一步骤,即使是在伪代码中。它应该是这样的: [x for x in list_of_common_factors if all elements of a are factors of x]

    我用嵌套的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 是我试图通过将上述代码转换为列表来生成的列表。如果可能的话,我该怎么做?

    2 回复  |  直到 7 年前
        1
  •  8
  •   Mehrdad Pedramfar    7 年前

    这就是您要寻找的:

    [x for x in list_of_common_factors if all(x % i==0 for i in a)]
    
        2
  •  1
  •   Mathieu    7 年前

    所以基本上,你需要一个函数,从一个数字列表中返回因子。此函数将返回一个列表。然后你只需要找到两个列表的交集。由于每个因素都是唯一的,我建议使用一套更有效的实现。要继续,代码如下所示:

    A = set(factors(#Input 1))
    B = set(factors(#Input 2))
    N = A.intersection(B)
    
        3
  •  1
  •   Pulsar    7 年前

    a A.

    from functools import reduce
    
    def gcd(x, y):    # greatest common divisor
       while y:
           x, y = y, x % y
       return x
    
    def lcm(x, y):    # least common multiple
       return (x*y)//gcd(x,y)
    
    lcm_of_a = reduce(lcm, a)  
    result = [x for x in list_of_common_factors if (x % lcm_of_a == 0)]