我有一个数字列表,可以从中提取所有这些数字的公因子。例如,从清单中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)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句