【发布时间】: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