python:拼合列表列表 [英] python: flatten list of lists OF LISTS
本文介绍了python:拼合列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道以前有人问过这个问题,但是当有类型列表时我没有看到任何解决方案:
I know this has been asked before but I don't see any solutions for when there is a list of the type:
original_list = [[1,2],[3],[4,5,[6]]]
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)
没有运气...提示?谢谢!
Not having any luck... tips? Thanks!
推荐答案
这些方面有问题吗?
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]
这篇关于python:拼合列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文