簡體   English   中英

將列表元素與同一列表中的其他元素相乘

[英]Multiply element of list with other elements in the same list

我想將列表的一個元素與所有其他元素相乘。

例如:

def product(a,b,c):
    return (a*b, a*c, a*b*c)

我已經做到了

def product(*args):
    list = []
    for index,element in enumerate(args):
        for i in args:
            if (args[index]*i) not in list:
                list.append(args[index]*i)
    return list

但這給了我[a*a, a*b,a*c, b*b]等。我不想要a*ab*bc*c放在那兒。

itertools是您的朋友在這里:

from itertools import combinations
from functools import reduce, partial
from operator import mul

# Make a sum-like function for multiplication; I'd call it product,
# but that overlaps a name in itertools and our own function
multiplyall = partial(reduce, mul)

def product(*args):
    # Loop so you get all two elements combinations, then all three element, etc.
    for n in range(2, len(args) + 1):
        # Get the combinations for the current combo count
        for comb in combinations(args, n):
            # Compute product and yield it
            # yielding comb as well just for illustration
            yield comb, multiplyall(comb)

我將其設置為一個生成器函數,因為坦率地說,幾乎所有只是逐個元素緩慢構建一個列表元素並返回它的函數實際上都應該是一個生成器函數(如果調用者想要一個列表,則只需執行mylist = list(generatorfunc(...)) ),使得在傳遞許多參數時更容易迭代使用而不會占用主內存。

用法示例:

>>> for pieces, prod in product(2, 3, 4):
        print ' * '.join(map(str, pieces)), '=', prod

哪個輸出:

2 * 3 = 6
2 * 4 = 8
3 * 4 = 12
2 * 3 * 4 = 24

你可以檢查是否平等

if (args[index]*i) not in list and args[index] != i:

因此,如果值為2, 3, 4, 5則只需要所有這些乘積:

2*3=6, 2*4=8, 2*5=10, 2*3*4=24, 2*3*5=30, 2*4*5=40, 2*3*4*5=120

這意味着取3, 4, 5所有組合,然后再乘以2 itertools模塊具有組合功能, reduce可與operator.mul結合使用來進行計算:

def product(first, *other):
    for n in range(1, len(other) + 1):
        for m in combinations(other, n):
            yield reduce(mul, m, first)

list(product(2, 3, 4, 5))

輸出:

[6, 8, 10, 24, 30, 40, 120]

您的列表中是否有重復的元素,例如[2, 3, 4, 2]

如果沒有,這里是一個襯板:

首先,用標簽來說明模式:

a = ['a1','a2','a3']

lsta = [[x+y for y in [z for z in a if z != x]] for x in a]
lsta

[['a1a2', 'a1a3'], ['a2a1', 'a2a3'], ['a3a1', 'a3a2']]

在這里,用數字:

a =[2,3,4,5]

print  [[x*y for y in [z for z in a if z != x]] for x in a]

[[6, 8, 10], [6, 12, 15], [8, 12, 20], [10, 15, 20]]

或產品總和,如果您希望:

a =[2,3,4,5]

print  [sum([x*y for y in [z for z in a if z != x]]) for x in a]

[24, 33, 40, 45]

如果列表重復,則變得更加復雜。 您是否要分別計算[2,3,4,2]2的第一次出現和第二次出現(即使您得到的值相同,出於某些目的,您可能仍需[2,3,4,2] )?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM