简体   繁体   中英

python generator does not work as my expectation

class ObjA(object):
    def __init__(self, self_id):
        self.id = self_id
        self.sub_items = []

    def __str__(self):
        return "objA{id=%d;sub_items=%s}" % (self.id, str(self.sub_items))

    __repr__ = __str__


lst = []
a1 = ObjA(1)
a1.sub_items.append(1)
a1.sub_items.append(2)
a2 = ObjA(2)
a2.sub_items.append(3)
lst.append(a1)
lst.append(a2)
result = {a.id: {tmp: a} for a in lst for tmp in a.sub_items}
print result

the result is:

{1: {2: objA{id=1;sub_items=[1, 2]}}, 
 2: {3: objA{id=2;sub_items=[3]}}};

but i want it like:

{1: {1: objA{id=1;sub_items=[1, 2]},
     2: objA{id=1;sub_items=[1, 2]}}, 
 2: {3: objA{id=2;sub_items=[3]}}};

something is wrong.

The nested comprehension you are looking for is the following:

{a.id: {tmp: a for tmp in a.sub_items} for a in lst}
# {1: {1: objA{id=1;sub_items=[1, 2]}, 
#      2: objA{id=1;sub_items=[1, 2]}}, 
#  2: {3: objA{id=2;sub_items=[3]}}}

Your original version is usually used to create a flat data structure. This leads to the key 1 being assigned a twice, keeping only the second value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM