Posted in Python onMarch 17, 2018
本文实例讲述了Python使用zip合并相邻列表项的方法。分享给大家供大家参考,具体如下:
1》使用zip()
函数和iter()
函数,来合并相邻的列表项
>>> 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)]
之所以会出现上述结果,是因为:
>>> [iter(x)]*3 [<listiterator object at 0x02F4D790>, <listiterator object at0x02F4D790>, <listiterator object at 0x02F4D790>]
可以看到,列表中的3个迭代器实际上是同一个迭代器!!!
2》 在1》的基础上,封装成一个函数,如下:
>>> 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()
函数和切片操作,来合并相邻的表项
>>> 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》的基础上,封装成函数,如下:
>>> 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()函数https://3water.com/article/136589.htm
python iter()函数https://3water.com/article/136587.htm
python lambda函数基础https://3water.com/article/136557.htm
python切片操作https://3water.com/article/136553.htm
希望本文所述对大家Python程序设计有所帮助。
Python使用zip合并相邻列表项的方法示例
- Author -
快递小可声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@