Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

python - How to loop through an object attribute with list comprehension?

I have a list - list_of_objects = [<obj1>,<obj2>]. Each object has an attribute <ob1j>.content. Each content attribute holds a list of dictionaries [{"key":"value"}, {"key":"value"}]. How do I use list comprehension to "unpack" these dictionaries into a single list? Example that doesn't work:

list_of_dictionaries = [dict for obj in list_of_objects for item in obj.content]

Basically I want to turn the below loop that works into a comprehension:

for obj in list_of_objects:
    new_list.extend(obj.content)
question from:https://stackoverflow.com/questions/65920250/how-to-loop-through-an-object-attribute-with-list-comprehension

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling dir on the object gives you back all the attributes of that object, including python special attributes.You can always filter out the special methods by using a list comprehension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...