问题在于索引编制。我已经尝试了以下代码片段:
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]
答案 0 :(得分:0)
您可以使用itertools multiset-receipt。它将生成更多所需的元组,您必须将其过滤掉:
`System.Linq.Dynamic.DynamicExpression.Parse(returnType, expression);`
输出:
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)
答案 1 :(得分:0)
因此,您尝试使用列表中所有可能的数字组合来获取所有产品。
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}
答案 2 :(得分:0)
我认为您想要的是每个数字的结果乘以列表中的其他整数吗?因此,对于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循环下