AkT*_*hao 6 python for-loop if-statement list-comprehension list
我有一个数字列表,我从中提取了所有这些数字的常见因素.例如,从列表中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_factors2和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)
Run Code Online (Sandbox Code Playgroud)
between_two_lists是我试图通过将上面的代码转换为列表理解来生成的列表.如果可能的话,我怎么能这样做呢?
这是你在寻找:
[x for x in list_of_common_factors if all(x % i==0 for i in a)]
Run Code Online (Sandbox Code Playgroud)