How to modify values in a list in pairs in python?… here is a solution to the problem.
How to modify values in a list in pairs in python?
I have the following code:
# 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)
Can I override it with single-row list initialization (and if not, what’s the most concise approach)? For example:
new_coords = [... for x, y in nums[::2], nums[1::2]]
Solution
You can compress slices of x and y in nested list understanding:
new_coords = [i for x, y in zip(coords[::2], coords[1::2]) for i in (transform_x(x), transform_y(y))]