Python使用zip合并相邻列表项的方法示例

当秋风吹过黄昏,树叶洒落了一地,透过树干间的缝隙,有一抹夕阳,在绽放他最后的美丽……

本文实例讲述了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.haodaima.com/article/136589.htm

python iter()函数//www.haodaima.com/article/136587.htm

python lambda函数基础//www.haodaima.com/article/136557.htm

python切片操作//www.haodaima.com/article/136553.htm

希望本文所述对大家Python程序设计有所帮助。

到此这篇关于Python使用zip合并相邻列表项的方法示例就介绍到这了。青春是气贯长虹,勇锐盖过怯懦,进取压倒苟安;如此锐气,弱冠后生有之,耳顺之年,则亦多见,年岁有如并非垂老,理想丢弃,方堕暮年。更多相关Python使用zip合并相邻列表项的方法示例内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

标签: Python zip