簡體   English   中英

python 多個列表的組合與乘法

[英]python combinations of multiple lists with multiplication

我有一組列表,如下所示:

a = ['a',2225, 0.063, 29.31]
b = ['b',5000, 0.072, 109]
c = ['c',6500, 0.051, 70]

我正在嘗試合並每個列表。 如果它是單個列表 ['a','b','c'],則可以使用 itertools.combinations 或 product。

但是,我如何將上面的三個列表組合在一起以包括某些元素的計算以及將名稱組合在一起? 下面顯示了我想要實現的目標。

['a',2225, 0.063, 29.31]
['b',5000, 0.072, 109]
['c',6500, 0.051, 70]
['ab', 7225, 0.0045, 138.31]
['ac', 8725, 0.0032, 99.31]
['bc', 11500, 0.0036, 179]
['abc', 13725, 0.0002, 208.31]

對於注釋column[0]已合並或添加在一起。 column[1]已添加在一起。 column[2]已相乘, column[3]已相加。

嘗試:

from math import prod
from itertools import combinations


a = ["a", 2225, 0.063, 29.31]
b = ["b", 5000, 0.072, 109]
c = ["c", 6500, 0.051, 70]

for i in range(1, 4):
    for x in combinations([a, b, c], i):
        v1, v2, v3, v4 = zip(*x)

        v1 = "".join(v1)
        v2 = sum(v2)
        v3 = prod(v3)
        v4 = sum(v4)

        print([v1, v2, v3, v4])

印刷:

['a', 2225, 0.063, 29.31]
['b', 5000, 0.072, 109]
['c', 6500, 0.051, 70]
['ab', 7225, 0.004536, 138.31]
['ac', 8725, 0.0032129999999999997, 99.31]
['bc', 11500, 0.0036719999999999995, 179]
['abc', 13725, 0.00023133599999999998, 208.31]

您可以使用itertools.combinationsfunctools.reduce

from functools import reduce
from itertools import combinations

a = ['a', 2225, 0.063, 29.31]
b = ['b', 5000, 0.072, 109]
c = ['c', 6500, 0.051, 70]

def merge(x, y): # defines rule to merge two lists
    return [x[0] + y[0], x[1] + y[1], x[2] * y[2], x[3] + y[3]]

def combine(lsts):
    for r in range(1, len(lsts) + 1):
        yield from (reduce(merge, lsts) for lsts in combinations(lsts, r))

for lst in combine([a, b, c]):
    print(lst)

# ['a', 2225, 0.063, 29.31]
# ['b', 5000, 0.072, 109]
# ['c', 6500, 0.051, 70]
# ['ab', 7225, 0.004536, 138.31]
# ['ac', 8725, 0.0032129999999999997, 99.31]
# ['bc', 11500, 0.0036719999999999995, 179]
# ['abc', 13725, 0.00023133599999999998, 208.31]

暫無
暫無

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

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