Python: can I have a list with named indices?

前端 未结 8 1607
天涯浪人
天涯浪人 2020-12-10 10:06

In PHP I can name my array indices so that I may have something like:

$shows = Array(0 => Array(\'id\' => 1, \'name\' => \'Sesame Street\'), 
               


        
8条回答
  •  心在旅途
    2020-12-10 10:34

    I did it like this:

    def MyStruct(item1=0, item2=0, item3=0):
        """Return a new Position tuple."""
        class MyStruct(tuple):
            @property
            def item1(self):
                return self[0]
            @property
            def item2(self):
                return self[1]
            @property
            def item3(self):
                return self[2]
        try:
            # case where first argument a 3-tuple                               
            return MyStruct(item1)
        except:
            return MyStruct((item1, item2, item3))
    

    I did it also a bit more complicate with list instead of tuple, but I had override the setter as well as the getter.

    Anyways this allows:

        a = MyStruct(1,2,3)
        print a[0]==a.item1
    

提交回复
热议问题