0

I have a simple Python class like this:

class P(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

I create a list of these objects e.g.:

import random

list_of_objects = [P(random.random(), random.random()) for i in range(1000)]

How do I then unpack the attributes of P into different lists?

That is, my goal is to obtain list_of_x, list_of_y, where these are defined as:

list_of_x = [p.x for p in list_of_objects]
list_of_y = [p.y for p in list_of_objects]

I was wondering if there was a cleaner way e.g. using zip/tuples, rather than the code above, which involves 2 for-loops.

akrylic
  • 53
  • 6

2 Answers2

0

There is always several ways to write something in a one-liner in Python, but I would not recommend it at all:

list_of_x, list_of_y = map(list, zip(*[p.__dict__.values() for p in list_of_objects]))

or more explicit:

list_of_x, list_of_y = map(list, zip(*[(p.x, p.y) for p in list_of_objects]))

Yet what you are doing is both clear and efficient, so I see no reason to write it in a one-liner. The above-mentioned implementations are not efficient since it involves additional copies to convert the list of pairs in two independent tuples, then to convert tuples in lists.

milembar
  • 919
  • 13
  • 17
0

Just use 1 for loop and append the x/y to empty lists:

list_of_x = []
list_of_y = []
for p in list_of_objects:
    list_of_x.append(p.x)
    list_of_y.append(p.y)
Terry Spotts
  • 3,527
  • 1
  • 8
  • 21
  • Not sure that's good advice, given how it spreads creation over multiple separate statements (so I wouldn't call it "cleaner") and appears to take about [twice as much time](https://tio.run/##fVHLbsMgELzzFXsECVmJcqkq5R9y6C2KELEh3co8hIlkvt4FY9dKmnYviJllZjT4FD@dPbz5ME06OAMRjcIIaLwLEYLySkay3qTtnCGk7eUwwIm665dqI3snkKdTGoRAi1EIOqhecxg5pIUtU8BmhCOMj1DKUCKkxyEKp0VVHTJ4PtFq2dSDMg5PAAPtAiCgLcxN0f1ut2MXQkocF/CGVvZ0CbE6lAxnn6OUt768ffK@PKynup7@WZ/tPlQI6aXXC70K/aW4lfaj00jvle1ozs1@sWljEyOkyIqtk8OSqcD6btvCrN3wGnszjDmdQUvr19Oyz8HezVWF41zu5u4D2kgjn0UbIaw0SojKV46RafoG). – superb rain Feb 19 '21 at 13:44