使用列表理解

时间:2019-02-17 13:54:03

标签: 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],那么我应该以{{1​​}}结尾,因为这些是[4, 8, 16]中的数字,其中2和4是因子。

但是,我正在努力弄清楚如何以列表理解(即使是伪代码)实现这一步骤。它看起来应该像这样:list_of_common_factors。我遇到麻烦的是if语句,因为我认为它应该包含for循环,但是我想不出一种简洁的编写方式。

使用嵌套的for循环,我设法做到了很长的路要走,

[x for x in list_of_common_factors if all elements of a are factors of x]

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) 是我试图通过将上面的代码转换为列表理解来生成的列表。如果可能的话,我该怎么办?

3 个答案:

答案 0 :(得分:8)

这就是您要寻找的:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

因此,基本上,您需要具有一个从数字列表返回因子的函数。该函数将返回一个列表。然后,您只需要找到两个列表的交集即可。由于每个因素都是唯一的,因此我建议使用一套有效的实现。要恢复,代码如下:

A = set(factors(#Input 1))
B = set(factors(#Input 2))
N = A.intersection(B)
相关问题