list 是 Python 中使用最频繁的数据类型, 标准库里面有丰富的函数可以使用.不过,如果把多维列表转换成一维列表(不知道这种需求多不多),还真不容易找到好用的函数,要知道Ruby.Mathematica.Groovy中可是有flatten的啊.如果列表是维度少的.规则的,还算好办例如: li=[[1,2],[3,4],[5,6]] print [j for i in li for j in i] #or from itertools import chain print list(cha
Python 代码阅读合集介绍:为什么不推荐Python初学者直接看项目源码 本篇阅读的代码实现了展开嵌套列表的功能,将一个嵌套的list展开成一个一维list(不改变原有列表的顺序). 本篇阅读的代码片段来自于30-seconds-of-python. flatten def flatten(lst): return [x for y in lst for x in y] # EXAMPLES flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6
1.递归yield使用: 嵌套列表展开 def flatten(nested): if type(nested)==list: for sublist in nested: for i in flatten(sublist): yield i else: yield nested print(list(flatten([[[1],2],3,4,[5,[6,7]],8]))) #结果为[1,2,3,4,5,6,7,8] 树的后序遍历: def postorderTraversal(self, ro
1.增加一个参数来控制缩进打印:level '''这是一个模块,可以打印列表,其中可能包含嵌套列表''' def print_list(the_list,level): """这个函数取一个位置参数the_list,他可以是任何列表,该列表中的每个数据都会递归地打印到屏幕上,各数据项各占一行; level参数用来在遇到嵌套列表时插入制表符,实现缩进打印.""" for each_item in the_list: if isinstance (e
#coding:utf-8 #创建简单的python列表 movies = ["The Holy Grail", "The Life of Brain", "The Meaning of Life"] #可以放在同一行,但分开会更易读 #和数组一样,列表的项从零开始 print movies[1] #>>>The Life of Brain print movies #>>>['The Holy Grail',