当前位置:首页 >> 脚本专栏

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()函数https://www.jb51.net/article/136589.htm

python iter()函数https://www.jb51.net/article/136587.htm

python lambda函数基础https://www.jb51.net/article/136557.htm

python切片操作https://www.jb51.net/article/136553.htm

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

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