展平包含整数的列表和整数列表

时间:2019-09-04 16:27:21

标签: python

您如何整理列表l

  l = [1,2,[3,4,5],6,7]

给出列表:

  [1,2,3,4,5,6,7]

这与展平不同:

  l = [[1],[2],[3,4,5],[6],[7]]

如此处所述:

How to make a flat list out of list of lists

在这种情况下,l仅包含一个int列表。

2 个答案:

答案 0 :(得分:1)

l = [1,2,[3,4,5],6,7] result =[] 

result = []

def flatten(lst):   
  for item in lst:
    if isinstance(item,list):
      flatten(item)
    else:
      result.append(item)

flatten(l)

print(result)

答案 1 :(得分:1)

您可以使用递归来解决此问题,该问题适用于任何迭代器:

l = [1, 2, [3, 4, 5], 6, 7, (8, 9, 10), set([11, 12]), 13, 14]

def flat(l):
    if not l:
        return l
    f = l[0]
    try:
        p = [i for i in f]
    except TypeError:
        # f is not iterable, so put it in a list.
        p = [f]
    return p + flat(l[1:])

print(flat(l))

输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]