本文实例讲述了Python使用zip合并相邻列表项的方法。分享给大家供大家参考,具体如下:
1》使用zip()
函数和iter()
函数,来合并相邻的列表项
1
2
3
4
5
6
7
8
|
>>> x [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] >>> zip ( * [ iter (x)] * 2 ) [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 ), ( 7 , 8 )] >>> zip ( * [ iter (x)] * 3 ) [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )] >>> zip ( * [ iter (x)] * 4 ) [( 1 , 2 , 3 , 4 ), ( 5 , 6 , 7 , 8 )] |
之所以会出现上述结果,是因为:
1
2
|
>>> [ iter (x)] * 3 [<listiterator object at 0x02F4D790 >, <listiterator object at0x02F4D790>, <listiterator object at 0x02F4D790 >] |
可以看到,列表中的3个迭代器实际上是同一个迭代器!!!
2》 在1》的基础上,封装成一个函数,如下:
1
2
3
4
5
6
7
8
9
|
>>> x [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] >>> group_adjacent = lambda a, k: zip ( * ([ iter (a)] * k)) >>> group_adjacent(x, 3 ) [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )] >>> group_adjacent(x, 2 ) [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 ), ( 7 , 8 )] >>> group_adjacent(x, 1 ) [( 1 ,), ( 2 ,), ( 3 ,), ( 4 ,), ( 5 ,), ( 6 ,), ( 7 ,), ( 8 ,), ( 9 ,)] |
3》使用zip()
函数和切片操作,来合并相邻的表项
1
2
3
4
5
6
7
8
9
10
|
>>> x [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] >>> zip (x[:: 2 ],x[ 1 :: 2 ]) [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 ), ( 7 , 8 )] >>> zip (x[ 0 :: 2 ],x[ 1 :: 2 ]) [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 ), ( 7 , 8 )] >>> zip (x[ 0 :: 3 ],x[ 1 :: 3 ],x[ 2 :: 3 ]) [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )] >>> zip (x[:: 3 ],x[ 1 :: 3 ],x[ 2 :: 3 ]) [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )] |
4》 在3》的基础上,封装成函数,如下:
1
2
3
4
5
6
7
8
9
|
>>> x [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] >>> group_adjacent = lambda a, k: zip ( * [a[i::k] for i in range (k)]) >>> group_adjacent(x, 3 ) [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )] >>> group_adjacent(x, 2 ) [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 ), ( 7 , 8 )] >>> group_adjacent(x, 1 ) [( 1 ,), ( 2 ,), ( 3 ,), ( 4 ,), ( 5 ,), ( 6 ,), ( 7 ,), ( 8 ,), ( 9 ,)] |
参考文章:
python zip()函数http://www.zzvips.com/article/134351.html
python iter()函数http://www.zzvips.com/article/134350.html
python lambda函数基础http://www.zzvips.com/article/134346.html
python切片操作http://www.zzvips.com/article/134345.html
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/sxingming/article/details/51476869