Reputation: 65
I have a list of objects that each contain several class variables. I'm interested in a couple of those class variables, and I'd like to create two separate lists, each containing a different class variable from that list of objects.
The object class looks something like this:
class Pie:
def __init__(self, array1, array2, timestamp, latitude, longitude):
self.array1 = array1
self.array2 = array2
self.timestamp = timestamp
self.latitude = latitude
self.longitude = longitude
And I have a list that contains a bunch of those objects:
list = [pie_instance1, pie_instance2, pie_instance3, pie_instance4, pie_instance5]
I'd like to create a list containing array1, and another list containing array2.
I started out just using list comprehension twice:
list_of_array1 = [x.array1 for x in list]
list_of_array2 = [x.array2 for x in list]
But it seems not so efficient to iterate over the entire list twice (the list in my actual code is very large).
So I tried this instead:
temp = np.array([[x.array1, x.array1] for x in list])
list_of_array1 = temp[:, 0]
list_of_array2 = temp[:, 1]
It works, but I'm wondering if there's a one-step way to achieve this with list comprehension? Or some other way you'd recommend? Thanks in advance!
Upvotes: 1
Views: 1392
Reputation: 23144
To iterate over list
only once, but create two result lists, use an ordinary for
loop:
list_of_array1 = []
list_of_array2 = []
for x in list:
list_of_array1.append(x.array1)
list_of_array2.append(x.array2)
But your original solution of using two list comprehensions was also fine. The performance difference is probably negligible.
Upvotes: 2
Reputation: 2442
The very definition of a list comprehension is to produce one list object.
Don't use list comprehensions here. Just use an ordinary loop:
list_of_array1 = []
list_of_array2 = []
for x in list:
list_of_array1.append(x.array1)
list_of_array2.append(x.array2)
This leaves you with just one loop to execute.
Upvotes: 5
Reputation: 156
You can use the zip
function:
L1, L2 = zip(*[(x.array1,x.array2) for x in list])
It's up to you to change the comprehension...
Upvotes: 3