如何在 python 二维元组中对具有相邻索引的元组进行分组?

cor*_*ped 2 python tuples

如何在 python 二维元组中对具有相邻索引的元组进行分组?

我还不熟悉 zip 功能。我已经写了这样的代码,但是效果不是很好。任何帮助,将不胜感激。谢谢你!!

coords = ((1, 2), (3, 4), (5, 6), (7, 8))
coords = tuple(zip(coords[0::2], coords[1::2]))
print(coords)
Run Code Online (Sandbox Code Playgroud)

实际输出:

(((1, 2), (3, 4)), ((5, 6), (7, 8)))
Run Code Online (Sandbox Code Playgroud)

预期输出:

((1, 2, 3, 4), (5, 6, 7, 8))
Run Code Online (Sandbox Code Playgroud)

atr*_*tru 8

你的代码就快到了。这是让它发挥作用的一种方法,

coords = ((1, 2), (3, 4), (5, 6), (7, 8))

coords = tuple(x + y for x, y in zip(coords[0::2], coords[1::2]))
Run Code Online (Sandbox Code Playgroud)

就像在您的代码中一样,它循环coords使用两个片段zip。但现在它获取两个切片 (xy) 的每个元素并将它们相加以形成 4 元素内部元组。