Python list comprehension for dictionaries in dictionaries?

后端 未结 5 2160
借酒劲吻你
借酒劲吻你 2021-01-03 19:46

I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something\'s bugging me.

In my test I have this kind of

5条回答
  •  情歌与酒
    2021-01-03 20:32

    Is there another way?

    Why not consider the use of some lightweight objects?

    You can still use list comprehensions for gathering or filtering the objects, and gain a lot in clarity / extensibility.

    >>> class Item(object):
    ...     def __init__(self, x, y, name):
    ...         self.x = x
    ...         self.y = y
    ...         self.name = name
    ... 
    >>> list_items = []
    >>> list_items.append(Item(x=70, y=60, name='test1420'))                        
    >>> list_items.append(Item(x=94, y=72, name='test277'))                         
    >>> items_matching = [item for item in list_items 
                          if 92 < item.x < 95 and 70 < item.y < 75]
    >>> for item in items_matching:
    ...     print item.name
    ... 
    test277
    >>> first_item = items_matching[0]
    >>> first_item.x += 50
    >>> first_item.x
    144
    

提交回复
热议问题