我正在尝试弄清楚如何展平整数或字符串列表。列表包含嵌套列表,例如,我想展平["cat", "dog", ["animal", "human"]]
之类的列表。
使用for循环时,我的doctest并非总是有效,即我分解了“ 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
此代码给我doctest 1和doctest 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']
任何帮助都将非常感谢
答案 0 :(得分:0)
您可以使用递归来实现:
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']