Python 在元组中解包元组
有关下列事项:Python 在元组中解包元组,python,tuples,unpack,Python,Tuples,Unpack,有关下列事项: tup = ((element1, element2),(value1, value2)) 我使用了: part1, part2 = tup tup_to_list = [*part1, *part2] 有没有更干净的方法?是否有“双重解包”?tup=part1+part2 python在添加过程中将元组对象添加到彼此后面如果您希望展平元组的常规元组,可以: 使用列表/生成器 platten\u tup=tuple(tup中的j代表i中的j代表i中的j) 使用itertoo
tup = ((element1, element2),(value1, value2))
我使用了:
part1, part2 = tup
tup_to_list = [*part1, *part2]
有没有更干净的方法?是否有“双重解包”?
tup=part1+part2
python在添加过程中将元组对象添加到彼此后面如果您希望展平元组的常规元组,可以:
platten\u tup=tuple(tup中的j代表i中的j代表i中的j)
导入itertools
展平\u tup=元组(itertools.chain.from\u iterable(tup))
如果使用循环没有什么害处,那么您可以试试这个
[tupl for tuploftupls in tup for tupl in tuploftupls]
这是同样的为了性能,如果我必须在小的
tup
s上重复执行这样的连接,我会选择内置函数,为它提供一个空的tuple作为起始值,即sum(tup,())
。否则,我会选择基于@Lucas的解决方案
性能比较 共性 小
tup
>env['tup']=tuple(2*(0,)表示范围(4)内的uuu)
>>>计时器(脚本、环境)
builtin_sum:`sum(tup,t0)`Itertools在这里可能会有更好的性能。这是一种方式。使用内置变量作为变量名几乎是一个普遍的坏主意。此外,变量名值
具有误导性,因为它是一个单数值。
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')