Reputation: 3314
I have two lists:
x_points = [0, 50, 100]
y_points = [10, 20, 30]
And I want to end up with a tuple of lists of the individual points, [x_i, y_i], like this: ([0, 10],[50, 20],[100, 30])
Is there an easier or more pythonic way than this enumeration?
result = tuple([x, y_points[i]] for i, x in enumerate(x_points))
Upvotes: 0
Views: 1935
Reputation: 11228
x_points = [0, 50, 100]
y_points = [10, 20, 30]
result = tuple(map(list,zip(x_points, y_points)))
print(result)
output
([0, 10], [50, 20], [100, 30])
Upvotes: 0
Reputation: 26039
Use zip
.
x_points = [0, 50, 100]
y_points = [10, 20, 30]
print(tuple([x, y] for x, y in zip(x_points, y_points)))
# ([0, 10], [50, 20], [100, 30])
Or:
tuple(map(list, zip(x_points, y_points)))
Upvotes: 2
Reputation: 168
You can even do
result=[(x_points[i],y_points[i]) for i in range(len(x_points))]
Upvotes: 0
Reputation: 26
This is extracted from the answer in the following post: How to merge lists into a list of tuples?
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> list(zip(list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
Upvotes: 0