你也可以尝试这个片段:
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, ...