Python: can I have a list with named indices?

前端 未结 8 1555
天涯浪人
天涯浪人 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
    
    0 讨论(0)
  • 2020-12-10 10:40

    @Unkwntech,

    What you want is available in the just-released Python 2.6 in the form of named tuples. They allow you to do this:

    import collections
    person = collections.namedtuple('Person', 'id name age')
    
    me = person(id=1, age=1e15, name='Dan')
    you = person(2, 'Somebody', 31.4159)
    
    assert me.age == me[2]   # can access fields by either name or position
    
    0 讨论(0)
  • 2020-12-10 10:46

    Yes,

    a = {"id": 1, "name":"Sesame Street"}
    
    0 讨论(0)
  • 2020-12-10 10:46

    Python has lists and dicts as 2 separate data structures. PHP mixes both into one. You should use dicts in this case.

    0 讨论(0)
  • 2020-12-10 10:50

    I think what you are asking is about python dictionaries.There you can named your indices as you wish . For ex:

    dictionary = {"name": "python", "age": 12}
    
    0 讨论(0)
  • 2020-12-10 10:58

    This sounds like the PHP array using named indices is very similar to a python dict:

    shows = [
      {"id": 1, "name": "Sesaeme Street"},
      {"id": 2, "name": "Dora The Explorer"},
    ]
    

    See http://docs.python.org/tutorial/datastructures.html#dictionaries for more on this.

    0 讨论(0)
提交回复
热议问题