Home > database >  python combinations of multiple lists with multiplication
python combinations of multiple lists with multiplication

Time:09-27

I have a group of lists, as the below:

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

I am trying to combine each of the lists. If it was a single list ['a','b','c'], then itertools.combinations or product could be used.

However, how would I bring together the three lists above to include calculations for some elements as well as bringing the names together? The below shows what i am trying to acheive.

['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]

for note column[0] has been combined or added together. column[1] has been added together. column[2] has been multiplied, column[3] has been added together.

CodePudding user response:

Try:

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])

Prints:

['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]

CodePudding user response:

You can use itertools.combinations and functools.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]
  • Related