问题描述
对于以下内容:
tup = ((element1,element2),(value1,value2))
我用过:
part1,part2 = tup
tup_to_list = [*part1,*part2]
有更简洁的方法吗?有没有“双开包”?
解决方法
如果您想展平一般的元组元组,您可以:
- 使用列表/生成器推导式
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在相加过程中将元组的对象相加
如果使用循环没有坏处,那么你可以试试这个
[tupl for tuploftupls in tup for tupl in tuploftupls]
这是同一种 question
,为了性能,如果我必须 重复 在小的 {{1 }}s,我会选择内置函数sum
,为它提供一个空元组作为起始值,即tup
。否则,我会选择基于 itertools.chain.from_iterable
的 @Lucas 解决方案。
性能比较。
共性
sum(tup,())
小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