python - 展平包含子列表的列表
问题描述
我试图弄清楚如何展平整数或字符串列表。列表包含嵌套列表,例如我想展平一个列表,例如["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']
任何帮助都会非常感谢
解决方案
您可以使用递归来做到这一点:
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']
推荐阅读
- django - Django:订单集查询
- python - 将 python matplotlib 子图添加到退出图不起作用
- javascript - 如何从评估函数返回变量?
- apache-spark - 窗口函数上的 pyspark case 语句
- spring-boot - 我需要一个 JwtDecoder bean,我可以自动配置它吗?
- gradle - 如何在 MSYS2 中安装 Gradle?
- amazon-web-services - certificatemanager:changeResourceRecordSets 用户无权访问此资源
- websphere - IBM Watson 实体和文字
- spring - 将大型应用程序从 spring 3.1.0.x 升级到 Spring Boot 版本?(我们无法决定) - 我应该遵循哪些最佳实践/程序?
- sql - 用于从表中返回特定列的 sql 查询