简体   繁体   English

在元组中解包元组

[英]Unpack tuples inside a tuple

For the following:对于以下内容:

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

I have used:我用过:

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

Is there a cleaner way to do so?有更清洁的方法吗? Is there "double unpacking"?有“双解包”吗?

If you're looking to flatten a general tuple of tuples, you could:如果您希望展平元组的一般元组,您可以:

  1. use a list/generator comprehension使用列表/生成器理解
flattened_tup = tuple(j for i in tup for j in i)
  1. use itertools使用迭代工具
import itertools
flattened_tup = tuple(itertools.chain.from_iterable(tup))

tup = part1+part2
python adds the objects of tuples behind each other during addition python 在添加过程中将元组的对象相互添加

If there is no harm in using loops then you could try this如果使用循环没有害处,那么你可以试试这个

[tupl for tuploftupls in tup for tupl in tuploftupls]

Here's the same kind of question这是同样的问题

For the sake of performance, if I had to repeatedly perform such concatenations over small tup s, I would go for the builtin function sum , providing it with an empty tuple as starting value, ie sum(tup, ()) .为了性能起见,如果我必须在小 tup 上tup执行此类连接,我将为内置 function sum提供 go ,并为其提供一个空元组作为起始值,即sum(tup, ()) Otherwise, I would go for itertools.chain.from_iterable -based solution of @Lucas.否则,我会 go 用于 @Lucas 基于itertools.chain.from_iterable的解决方案。


Performance comparisons.性能比较。

Commonalities共同点

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

Small tuptup

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

Not small tup不小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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM