I was wondering how to simplify the following python code. I tried to loop it but it didn't quite work out and I thought there must be a way without repeating the same thing over and over again.
coordinates = [
(9, 2, 17),
(4, 14, 11),
(8, 10, 6),
(2, 7, 0)
]
cdns = coordinates[0][0:2], coordinates[1][0:2], coordinates[2][0:2], coordinates[3][0:2]
newCnds = tuple(cdns)
newCnds
CodePudding user response:
You can use numpy
:
>>> import numpy as np
>>> coordinates = [
... (9, 2, 17),
... (4, 14, 11),
... (8, 10, 6),
... (2, 7, 0)
... ]
>>> coordinates_np = np.array(coordinates)
>>> coordinates_np[:, 0:2]
array([[ 9, 2],
[ 4, 14],
[ 8, 10],
[ 2, 7]])
In general specifically for vectorized computation - numpy
would be the best choice, both in terms of simplicity and speed.
CodePudding user response:
Use list comprehension
coordinates = [
(9, 2, 17),
(4, 14, 11),
(8, 10, 6),
(2, 7, 0)
]
newCnds = [i[:2] for i in coordinates]