【问题标题】:Unpack tuples inside a tuple在元组中解包元组
【发布时间】:2021-08-05 23:43:56
【问题描述】:

以下:

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

我用过:

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

有更清洁的方法吗?有没有“双重拆包”?

【问题讨论】:

    标签: python tuples unpack


    【解决方案1】:

    tup = part1+part2
    python在添加过程中将元组的对象相互添加

    【讨论】:

      【解决方案2】:

      如果您希望扁平化元组的一般元组,您可以:

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

      【讨论】:

      • Itertools 在这里可能会有更好的性能。
      • 就是这样。
      【解决方案3】:

      如果使用循环没有害处,那么你可以试试这个

      [tupl for tuploftupls in tup for tupl in tuploftupls]
      

      这里是同一种question

      【讨论】:

      • 使用内置函数作为变量名几乎普遍是个坏主意。此外,变量名称 values 具有误导性,因为它是一个奇异值。
      【解决方案4】:

      为了性能,如果我不得不 重复 在小的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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-05
        • 2015-05-15
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多