[英]python combinations of multiple lists with multiplication
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.
如果它是单个列表 ['a','b','c'],则可以使用 itertools.combinations 或 product。
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[0]
已合并或添加在一起。 column[1]
has been added together. column[1]
已添加在一起。 column[2]
has been multiplied, column[3]
has been added together. column[2]
已相乘, column[3]
已相加。
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]
You can use itertools.combinations
and functools.reduce
:您可以使用
itertools.combinations
和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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.