首页 > 代码库 > 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合并相邻的列表项
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。