python - python:展平列表列表的列表
问题描述
我知道以前有人问过这个问题,但是当有类型列表时,我没有看到任何解决方案:
original_list = [[1,2], [3], [4,5,[6]]]
试过这个方法:
def flatten(list):
"""Given a list that contains elements and other lists, this
will return a new list that has no sublists ("flattened")"""
flat = [] # new empty list to populate with flattened list
for sublist in list: # iterate through list elements
for element in sublist: #
flat.append(element)
return flat
print(flatten([1,2,3]))
这个方法也是:
old_list = [[1,2], [3], [4,5,[6]]]
flat1 = []
flat1 = [sum(old_list, [])] # 1 layer deep
flat2 = []
flat2 = [sum(flat1), []] # 2 layers deep
print(sort2)
没有任何运气...提示?谢谢!
解决方案
这些方面的东西?
In [6]: original_list = [[1,2], [3], [4,5,[6]]]
In [7]: def flatten(potential_list):
...: new_list = []
...: for e in potential_list:
...: if isinstance(e, list):
...: new_list.extend(flatten(e))
...: else:
...: new_list.append(e)
...: return new_list
...:
In [8]: flatten(original_list)
Out[8]: [1, 2, 3, 4, 5, 6]
推荐阅读
- laravel - Laravel 在状态更改时发送邮件
- ios - WebRTC 使用位码构建。最后一步失败
- sql - 需要帮助将自定义月份汇总到快照字段中
- plaid - 用户连接银行账户 2 分钟后格子交易不可用 (PRODUCT_NOT_READY)
- ios - 突然詹金斯不再做 pod install
- javascript - 使用简单功能查看 div 时出现问题
- google-cloud-platform - 在不访问 Billing API 的情况下监控 GCP 支出
- c# - 使用 NewtonSoft.JSON 在 C# 中的属性名称中反序列化带有破折号(Kebab 案例)的 JSON
- java - 有人可以看看我的 atm 项目代码吗?
- c - AVRDUDE 在 atmega32 上缓慢上传