开发者

General method for unpacking and combining nested tuples

开发者 https://www.devze.com 2023-03-02 13:32 出处:网络
I\'ve generated the cartesian product of three dicts thus: import itertools combined = list(itertools.product(foo, bar, baz))

I've generated the cartesian product of three dicts thus:

import itertools
combined = list(itertools.product(foo, bar, baz))

So my list now looks like:

[(('text a', 'value a'), ('text b', 'value b'), 开发者_StackOverflow中文版('text c', 'value c')), … ]

What I want to do is unpack this list such that I end up with a list of lists containing the flattened nested tuples' text and values:

[['text a text b text c', 'value a value b value c'], … ]

Is there an efficient general method for doing this?

Follow-up (having seen Dan D.'s answer):

What if my tuples looked like

(('text a', float a), ('text b', float b), ('text c', float c ))

and I wanted to add the floats instead of concatenating the values?


map(lambda v: map(' '.join, zip(*v)), combined)


You don't have to cram everything on one line:

def combine(items):
    for tuples in items:
        text, numbers = zip(*tuples)
        yield ' '.join(text), sum(numbers)

print list(combine(product( ... )))


Here's a generalization:

def combine(functions, data):
    for elements in data:
        yield [f(e) for f, e in zip(functions, zip(*elements))]

# A simple function for demonstration.
def pipe_join(args):
    return '|'.join(args)

some_data = [
    (('A', 10), ('B', 20), ('C', 30)),
    (('D', 40), ('E', 50), ('F', 60)),
    (('G', 70), ('H', 80), ('I', 90)),
]

for c in combine( [pipe_join, sum], some_data ):
    print c


What if my tuples looked like

combined = (('text a', float a), ('text b', float b), ('text c', float c ))

and I wanted to add the floats instead of concatenating the values?

Try using the built-in sum() function:

sum(x for (_,x) in combined)
0

精彩评论

暂无评论...
验证码 换一张
取 消