[英]List comprehension to find all multiples of each number in list less than a number
I'm trying to write a function that will find all numbers that are a multiple of at least one number in a list where the multiple is less than a certain number. 我正在尝试编写一个函数,该函数将查找列表中至少有一个数字的倍数的所有数字,其中倍数小于某个数字。 Here's what I've tried so far: 这是我到目前为止所尝试的:
def MultiplesUnderX(MultArray,X):
'''
Finds all the multiples of each value in MultArray that
are below X.
MultArray: List of ints that multiples are needed of
X: Int that multiples will go up to
'''
return [i if (i % x == 0 for x in MultArray) else 0 for i in range(X)]
For example, MultiplesUnderX([2,3],10) would return [2,3,4,6,8,9]. 例如,MultiplesUnderX([2,3],10)将返回[2,3,4,6,8,9]。 I'm a little unsure how to do this with the for loop inside of the list comprehension. 我有点不确定如何使用列表理解中的for循环来完成此操作。
You can use the Python any() function to check if there is at least one instance of a divider in MultArray: 您可以使用Python any()函数来检查MultArray中是否至少有一个分隔符实例:
def MultiplesUnderX(MultArray,X):
return [i for i in range(X) if any(i % x == 0 for x in MultArray)]
You can use the Python built-in function any
which returns True
if the iterable passed in contains any truth-y values in combination with a conditional at the end of the list comprehension limiting the list to only elements that satisfy the any
call. 您可以使用Python内置函数any
它返回True
如果传入的迭代器包含在列表理解限制列表,只有满足元素结束结合有条件任何真y值any
电话。
def get_multiples_under(factors, max):
return [i for i in xrange(1, max) if any(i % factor == 0 for factor in factors)]
Your desired output is shown as such: 您所需的输出显示如下:
multiples = [2, 3]
print get_multiples_under(multiples, 10)
# [2, 3, 4, 6, 8, 9]
Another version of this algorithm which may be more efficient if the list is mostly co-prime, you can just use range(i, X, i)
to generate only the multiples of i
, then use heapq.merge
to merge the iterators such that the iterator returned is sorted. 如果列表主要是co-prime,这个算法的另一个版本可能更有效,你可以只使用range(i, X, i)
来生成i
的倍数,然后使用heapq.merge
来合并迭代器,这样返回的迭代器已排序。
The last step is to eliminate duplicates as you go: 最后一步是消除重复:
import heapq
def all_multiples(multi_list, max_N):
gens = []
for fac in sorted(set(multi_list)):
# In Python 3 this is a generator of all multiples of "fac" less
# than max_N. In Python 2 use xrange
gens.append(range(fac, max_N, fac))
# This will do a heap merge on the generators (which are already sorted)
o = heapq.merge(*gens)
last = None
for val in o:
if val != last:
yield val
last = val
if __name__ == "__main__":
multi_list = [2, 4, 7]
print(list(all_multiples(multi_list, 12)))
# [2, 4, 6, 7, 8, 10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.