[英]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:如果您希望展平元组的一般元组,您可以:
flattened_tup = tuple(j for i in tup for j in i)
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 在添加过程中将元组的对象相互添加
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 tup
小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
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.