I have a list of objects:
[Object_1, Object_2, Object_3]
Each object has an attribute: time:
Object_1.time = 20
Object_2.time = 30
Object_3.time = 40
I want to create a list of the time attributes:
[20, 30, 40]
What is the most efficient way to get this output? It can't be to iterate over the object list, right?:
items = []
for item in objects:
items.append(item.time)
List comprehension is what you're after:
list_of_objects = [Object_1, Object_2, Object_3]
[x.time for x in list_of_objects]
from operator import attrgetter
items = map(attrgetter('time'), objects)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With