【问题标题】:Find elements in a list of which all elements in another list are factors, using a list comprehension使用列表推导查找列表中的元素,其中另一个列表中的所有元素都是因子
【发布时间】:2019-02-17 13:54:02
【问题描述】:

我有一个数字列表,我从中提取了所有这些数字的公因数。例如,从列表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 是我试图通过将上述代码转换为列表理解来生成的列表。如果可能的话,我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    这就是你要找的东西:

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

    【讨论】:

      【解决方案2】:

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

      A = set(factors(#Input 1))
      B = set(factors(#Input 2))
      N = A.intersection(B)
      

      【讨论】:

      • OP 希望它具有列表理解能力。
      • @MehrdadPedramfar 这不是这个问题的最佳选择。那么,为什么提出其他 OP 可能不知道的东西是错误的呢?
      【解决方案3】:

      首先计算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)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 2020-07-07
        • 2020-09-25
        • 2019-12-22
        • 2011-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多