【问题标题】:How to flatten a list with various data types (int, tuple)如何展平具有各种数据类型(int、tuple)的列表
【发布时间】:2014-04-29 10:19:47
【问题描述】:

假设我有一个包含一个或多个元组的列表:

[0, 2, (1, 2), 5, 2, (3, 5)]

摆脱元组使其只是一个 int 列表的最佳方法是什么?

[0, 2, 1, 2, 5, 2, 3, 5]

【问题讨论】:

  • 这不是真正的问题,因为不是每个内部元素都是元组。
  • 那么请考虑下面我的递归解决方案! :)
  • 下面的答案会起作用,但在你在代码中交换其中一个之前,先问问自己为什么你有一个这样的列表。如果您可以使原始列表同质化,您的代码将更容易理解。
  • 是的,考虑到我的通用解决方案适用于任何数据类型和任何深度。 :)

标签: python list tuples flatten


【解决方案1】:

一种解决方案(使用itertools.chain):

>>> from itertools import chain
>>> l = [0, 2, (1, 2), 5, 2, (3, 5)]
>>> list(chain(*(i if isinstance(i, tuple) else (i,) for i in l)))
[0, 2, 1, 2, 5, 2, 3, 5]

【讨论】:

    【解决方案2】:

    使用嵌套列表推导:

    >>> lst = [0, 2, (1, 2), 5, 2, (3, 5)]
    >>> [y for x in lst for y in (x if isinstance(x, tuple) else (x,))]
    [0, 2, 1, 2, 5, 2, 3, 5]
    

    【讨论】:

      【解决方案3】:
      def untuppleList(lst):
          def untuppleList2(x):
              if isinstance(x, tuple):
                  return list(x)
              else:
                  return [x]
          return [y for x in lst for y in untuppleList2(x)]
      

      那你就可以untuppleList([0, 2, (1, 2), 5, 2, (3, 5)])了。

      【讨论】:

        【解决方案4】:

        一个更通用的递归解决方案,应该适用于任何可迭代(字符串除外)和任何深度的元素:

        import collections
        
        def flatten(iterable):
            results = []
            for i in iterable:
                if isinstance(i, collections.Iterable) and not isinstance(i, basestring):
                    results.extend(flatten(i))
                else:
                    results.append(i)
            return results
        

        及用法:

        >>> flatten((1, 2, (3, 4), ('happy')))
        [1, 2, 3, 4, 'happy']
        >>> flatten((1, 2, (3, 4, (5, 6)), ('happy'), {'foo': 'bar', 'baz': 123}))
        [1, 2, 3, 4, 5, 6, 'happy', 'foo', 'baz']
        

        【讨论】:

        • 我只接受 ndpu 的回答,因为它更适合我的特定数据集,但我可以看到您的解决方案作为一种通用方法非常有用。
        【解决方案5】:

        您可以使用我的funcy 库中的flatten 函数:

        from funcy import flatten
        flat_list = flatten(your_list)
        

        你也可以偷看its implementation

        【讨论】:

          猜你喜欢
          • 2010-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-17
          相关资源
          最近更新 更多