【发布时间】:2021-08-05 23:43:56
【问题描述】:
以下:
tup = ((element1, element2),(value1, value2))
我用过:
part1, part2 = tup
tup_to_list = [*part1, *part2]
有更清洁的方法吗?有没有“双重拆包”?
【问题讨论】:
以下:
tup = ((element1, element2),(value1, value2))
我用过:
part1, part2 = tup
tup_to_list = [*part1, *part2]
有更清洁的方法吗?有没有“双重拆包”?
【问题讨论】:
tup = part1+part2
python在添加过程中将元组的对象相互添加
【讨论】:
如果您希望扁平化元组的一般元组,您可以:
flattened_tup = tuple(j for i in tup for j in i)
import itertools
flattened_tup = tuple(itertools.chain.from_iterable(tup))
【讨论】:
【讨论】:
values 具有误导性,因为它是一个奇异值。
为了性能,如果我不得不 重复 在小的tup上执行这样的连接 s,我会选择内置函数sum,为它提供一个空元组作为起始值,即sum(tup, ())。否则,我会选择@Lucas 的基于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
【讨论】: