首页 > 代码库 > python 使用zip合并相邻的列表项

python 使用zip合并相邻的列表项

1 >>> a = [1, 2, 3, 4, 5, 6]
2 >>> zip(*([iter(a)] * 2))
3 [(1, 2), (3, 4), (5, 6)]

函数形式:

1 >>> group_adjacent = lambda a, k: zip(*([iter(a)] * k))
2 >>> group_adjacent(a, 3)
3 [(1, 2, 3), (4, 5, 6)]
4 >>> group_adjacent(a, 2)
5 [(1, 2), (3, 4), (5, 6)]
6 >>> group_adjacent(a, 1)
7 [(1,), (2,), (3,), (4,), (5,), (6,)]

切片形式:

1 >>> zip(a[::2], a[1::2])
2 [(1, 2), (3, 4), (5, 6)]
3  
4 >>> zip(a[::3], a[1::3], a[2::3])
5 [(1, 2, 3), (4, 5, 6)]

列表推导式:

1 >>> group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))
2 >>> group_adjacent(a, 3)
3 [(1, 2, 3), (4, 5, 6)]
4 >>> group_adjacent(a, 2)
5 [(1, 2), (3, 4), (5, 6)]
6 >>> group_adjacent(a, 1)
7 [(1,), (2,), (3,), (4,), (5,), (6,)]

 

python 使用zip合并相邻的列表项