解包元组内的元组

Unpack tuples inside a tuple

对于以下内容:

tup = ((element1, element2),(value1, value2))

我用过:

part1, part2 = tup
tup_to_list = [*part1, *part2]

有没有更简洁的方法?有没有“双拆包”?

tup = part1+part2
python 加法时元组的对象依次相加

如果您想要展平元组的一般元组,您可以:

  1. 使用list/generator理解
flattened_tup = tuple(j for i in tup for j in i)
  1. 使用 itertools
import itertools
flattened_tup = tuple(itertools.chain.from_iterable(tup))

如果使用循环没有坏处,那么你可以试试这个

[tupl for tuploftupls in tup for tupl in tuploftupls]

这里有同款question

为了性能,如果我不得不重复在小tups上执行这样的连接,我会选择@Lucas的内置函数sum, providing it with an empty tuple as starting value, i.e. sum(tup, ()). Otherwise, I would go for itertools.chain.from_iterable解决方案。


性能比较。

共同点

import itertools
import timeit

scripts = {
    'builtin_sum'         : "sum(tup, t0)",
    'chain_from_iterable' : "(*fi(tup),)",
    'nested_comprehension': "[tupl for tuploftupls in tup for tupl in tuploftupls]",
}
env = {
    'fi' : itertools.chain.from_iterable,
    't0' : (),
}
def timer(scripts, env):
    for u, s in scripts.items():
        print(u, f': `{s}`')
        print(f'\t\t{timeit.timeit(s, globals=env):0.4f}s')

tup

>>> env['tup'] = tuple(2*(0,) for _ in range(4))
>>> timer(scripts, env)
builtin_sum : `sum(tup, t0)`  
        0.2976s
chain_from_iterable : `(*fi(tup),)`  
        0.4653s
nested_comprehension : `[tupl for tuploftupls in tup for tupl in tuploftupls]`
        0.7203s

不小tup

>>> env['tup'] = tuple(10*(0,) for _ in range(50))
>>> timer(scripts, env)
builtin_sum : `sum(tup, t0)`
        63.2285s
chain_from_iterable : `(*fi(tup),)`  
        11.9186s
nested_comprehension : `[tupl for tuploftupls in tup for tupl in tuploftupls]`  
        20.0901s