首页 > 解决方案 > 展平包含子列表的列表

问题描述

我试图弄清楚如何展平整数或字符串列表。列表包含嵌套列表,例如我想展平一个列表,例如["cat", "dog", ["animal", "human"]].

当使用 for 循环时,我的 doctests 并不总是有效,即我得到了“cat”的分解,在我的新列表中,我将“c”、“a”、“t”添加到了我创建的空列表中,而不是单词“猫”。对于非嵌套列表中的整数,我也会收到一条错误消息'int' object not iterable

def flatten_lists(nested):
    '''(list) -> list
    For any nested list in a list, we want to form
    one single list containing all values of the list and sublist

    >>> flatten_lists([3, 4, 5, 6, 7])
    [3, 4, 5, 6, 7]
    >>> flatten_lists([[1]])
    [1]
    >>> flatten_lists(["cat", "dog", ["animal", "human"]])
    ["cat", "dog", "animal", "human"]
    '''
    flattened_list = []
    for sublist in nested:
        for item in sublist:
            flattened_list.append(item)
    return flattened_list

此代码为我提供了 doctests 1 和 3 的以下错误([[1]] 有效):

flatten_lists([3, 4, 5, 6, 7]):

TypeError: 'int' object is not iterable

flatten_lists(["cat", "dog", ["animal", "human"]])

预期的:

["cat", "dog", "animal", "human"]

得到:

['c', 'a', 't', 'd', 'o', 'g', 'animal', 'human']

任何帮助都会非常感谢

标签: python

解决方案


您可以使用递归来做到这一点:

def flatten_lists(lst):
  result = []
  for elem in lst:
    if isinstance(elem, list):
      result = result + flatten_lists(elem)
    else:
      result.append(elem)
  return result

r = flatten_lists(["cat", "dog", ["animal", "human"]])
print(r)

这将返回:

['cat', 'dog', 'animal', 'human']

推荐阅读