1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#1.分割大列表为三个元素的小列表,不够三个元素的亦当成一个列表输出 In [ 17 ]: lst Out[ 17 ]: [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] In [ 18 ]: for i in range ( 0 , len (lst), 3 ): ...: print lst[i:i + 3 ] ...: [ 0 , 1 , 2 ] [ 3 , 4 , 5 ] [ 6 , 7 , 8 ] [ 9 ] #2.稍微改进下,用了个列表推导,结果都放到一个列表了 In [ 35 ]: lst Out[ 35 ]: [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] In [ 36 ]: b = [lst[i:i + 3 ] for i in range ( 0 , len (lst), 3 )] In [ 37 ]: b Out[ 37 ]: [[ 0 , 1 , 2 ], [ 3 , 4 , 5 ], [ 6 , 7 , 8 ], [ 9 ]] In [ 38 ]: #3.不太喜欢的lambda,猛一看不懂,再细看逻辑还是上面的逻辑 In [ 10 ]: f = lambda a: map ( lambda b:a[b:b + 3 ], range ( 0 , len (a), 3 )) In [ 11 ]: lst Out[ 11 ]: [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] In [ 12 ]: f(lst) Out[ 12 ]: [[ 0 , 1 , 2 ], [ 3 , 4 , 5 ], [ 6 , 7 , 8 ], [ 9 ]] |