这里定义了两个全局的变量countx 和 county
#!/usr/bin/env python
#__metaclass__ = type
nest = [[1,2],[3,4],5]
countx = 0
county = 0
def flatten(nested):
try:
for sublist in nested:
print 'sublist=',sublist
# global countx
# print 'countx = %i' % countx
# countx += 1
for element in flatten(sublist):
print 'element=',element
# global county
# print 'county = %i' % county
# county += 1
yield element
except TypeError:
print 'except'
# print countx,county
yield nested
本文介绍了一个用于将嵌套列表转换为扁平列表的Python算法。通过递归方式遍历多级嵌套列表,并逐个元素地返回展开后的列表内容。文中包含了一个具体的Python函数实现示例。
24万+

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



