simplify python code – slice several lists and turn into tuple

Question:

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
Asked By: ghosty

||

Answers:

Use list comprehension

coordinates = [
    (9, 2, 17),
    (4, 14, 11),
    (8, 10, 6),
    (2, 7, 0)
]
newCnds = [i[:2] for i in coordinates]
Answered By: SollyBunny

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.

Answered By: Grzegorz Skibinski
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.