你也可以尝试这个片段:
from collections import Iterable
ellipsis = type('',(),{'__str__' : lambda self:'...'})()
def flatten(collection,stack = None):
if not stack: stack = set()
if id(collection) in stack:
yield ellipsis
return
for item in collection:
if isinstance(item,Iterable):
stack.add(id(collection))
for subitem in flatten(item,stack):
yield subitem
stack.remove(id(collection))
else: yield item
x = [1,2,[3,4,[5],[[6]],7]]
x.append(x)
>>> print(', '.join(map(str,flatten(x))))
1, 2, 3, 4, 5, 6, 7, ...
Python中列表扁平化与join方法应用
博客展示了Python代码片段,定义了flatten函数用于列表扁平化处理,避免循环引用问题。通过该函数将嵌套列表展开,最后使用join方法将扁平化后的列表元素以逗号连接输出,体现了Python列表操作的技巧。
14万+

被折叠的 条评论
为什么被折叠?



