![](/img/trans.png)
[英]Determine list of all possible products from a list of integers in Python
[英]Get all of the possible products from a list of numbers
問題是索引。 我試過這個代碼片段:
for i in range(2,len(the_list_im_getting_values_from)):
for j in range(0,i+1):
index[j] = j
for k in range(0,len(index)):
the_output_list.append(the_list_im_getting_values_from[index[k]]*the_list_im_getting_values_from[index[k+1]])
k += 1
,但它完全沒有用。
如何解決這個問題呢?
示例輸入:3、4 和 7 的數組
示例輸出:[12,21,28,84]
處理階段:
3*4=12
3*7=21
4*7=28
3*4*7=84
[12,21,28,84]
您可以使用 itertools multiset-receipt 。 它將生成更多所需的元組,您必須將它們過濾掉:
from itertools import chain, combinations
# see link above for credits
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
def mult(iterab):
"""Multiply all numbers in the iterable and return result"""
rv = 1
for k in iterab:
rv = rv * k
return rv
d = [3,4,7]
k = powerset(d) # (), (3,), (4,), (7,), (3, 4), (3, 7), (4, 7), (3, 4, 7)
result = []
# we filter out anything from k thats shorter then 2
result.extend(map(mult, (x for x in k if len(x)>1)))
print(result)
輸出:
[12, 21, 28, 84]
因此,您正在嘗試使用列表中所有可能的數字組合來獲取所有產品。
from itertools import chain, combinations
from functools import reduce
def powerset(iterable, min_subset_size=1):
'Returns all subsets of the iterable larger than the given size.'
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(min_subset_size, len(s)+1))
def product(iterable):
'Returns the product of all the numbers in the iterable.'
return reduce((lambda x, y: x * y), iterable)
numbers = 3, 4, 7
如果例如 3 算作單個數字的乘積:
result = {product(subset) for subset in powerset(numbers)}
print(result)
Out: {3, 4, 7, 12, 84, 21, 28}
如果產品必須是 2 個或更多數字,例如 3*4、3*4*7:
result = {product(subset) for subset in powerset(numbers, 2)}
print(result)
Out: {28, 12, 21, 84}
我想你想要的是每個數字乘以列表中其他整數的結果? 因此對於 list[3,4,7] 你會想要 9,16,49,12,21,28。 你可以試試這個。
l = [3,4,7]
s = set()
for count, num in enumerate(l):
for each in l:
s.add(each * l[count])
s
{9, 12, 16, 49, 21, 28}
如果你不想要方塊 (9,49,16) 添加
if list[count] == each:
countinue
在第二個 for 循環下面
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.