天宫鹤

Python使用普通函数模拟生成器

def flatten(nested):
    result = []
    try:
        # 不迭代类似于字符串的对象
        try:
            nested + ''
        except TypeError:
            pass
        else:
            raise TypeError
        for sublist in nested:
            for element in flatten(sublist):
                result.append(element)
    except TypeError:
        result.append(nested)
    return result

 

posted on 2024-08-15 21:35  GoGrid  阅读(6)  评论(0编辑  收藏  举报

导航