本文实例讲述了Python使用zip合并相邻列表项的方法。分享给大家供大家参考,具体如下:1
本文实例讲述了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()函数//www.jb51.net/article/136589.htm
python iter()函数//www.jb51.net/article/136587.htm
python lambda函数基础//www.jb51.net/article/136557.htm
python切片操作//www.jb51.net/article/136553.htm
Python zip 合并 相邻列表项