我有以下代码:
# defines a square with 4 vertices: (1, 1), (1, 5), (5, 5), (5, 1)
coords = [1, 1, 1, 5, 5, 5, 5, 1]
new_coords = []
for i in range(0, len(coords), 2):
x = transform_x(coords[i])
y = transform_y[coords[i + 1])
new_coords.append(x)
new_coords.append(y)
我可以使用单行列表初始化重写它吗(如果不能,最简洁的方法是什么)?例如:
new_coords = [... for x, y in nums[::2], nums[1::2]]
最佳答案
您可以在嵌套列表理解中压缩 x 和 y 的切片:
new_coords = [i for x, y in zip(coords[::2], coords[1::2]) for i in (transform_x(x), transform_y(y))]
关于python - 如何在 python 中成对修改列表中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55487662/