'Access indices of variables with a list comprehension
I've defined these six points in a coordinate system:
P1 = (0,0)
P2 = (0,-2)
P3 = (4,-2)
P4 = (4,0)
P5 = (4,2)
P6 = (2,1)
Now, I'd like to make a list of all the x-coordinates with a for loop reading the indices.
Something like this:
[P[i+1][0] for i in range(6)]
to get the result [0, 0, 4, 4, 4, 0]. How do I make Python read the P[i+1] as P1, P2, P3...?
Solution 1:[1]
To use your P[i+1] indexing I would suggest a dict where the keys are indices in range [1, 7) and the values are your points.
# P = {1: (0,0), 2: (0,-2), 3: (4,-2) ...}
P = dict(zip(range(1,7), [(0,0), (0,-2), (4,-2), (4,0), (4,2), (0,2)]))
x_coord = [P[i+1][0] for i in range(6)]
print(x_coord)
However if you only want the x coordinate of each tuple you could go for something like this:
points = [(0,0), (0,-2), (4,-2), (4,0), (4,2), (0,2)]
x_coords = ...
print(x_coords)
You could go for either this:
x_coords = [x for x,_ in points]
or:
x_coords = list(map(lambda x:x[0], points))
Output:
[0, 0, 4, 4, 4, 0]
Solution 2:[2]
You want Python to
read the P[i+1] as P1, P2, P3...
So, the main point is using f"P{i+1}" to produce P1, P2, .... Then, I suggest you use these as keys to a dictionary. This way, your code works even when the number of points is changed.
points = {'P1': (0,0), 'P2': (0,-2), 'P3': (4,-2), 'P4': (4,0), 'P5': (4,2), 'P6': (2,1)}
Assume the number of points is 6:
indices = range(1, 7)
Now you can have a list of X's:
Print([points[f"P{index}"][0] for index in indices])
Output:
[0, 0, 4, 4, 4, 2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
