从数字列表中获取所有可能的产品

2024-04-20 14:12:19 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是索引。我尝试了以下代码片段:

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]

Tags: the代码infrom示例foroutputindex
3条回答

您可以使用itertoolsmultiset-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}

我想你想要的是每个数字乘以列表中其他整数的结果?因此,对于列表[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循环下面

相关问题 更多 >