【问题标题】:Python: can I have a list with named indices?Python:我可以有一个带有命名索引的列表吗?
【发布时间】:2010-09-15 17:53:43
【问题描述】:

在 PHP 中,我可以命名我的数组索引,这样我就可以有类似的东西:

$shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'), 
               1 => Array('id' => 2, 'name' => 'Dora The Explorer'));

这在 Python 中可行吗?

【问题讨论】:

  • 你应该阅读python tutorial和esp。关于datastructures 的部分还包括dictionaries.
  • 为了帮助未来的谷歌搜索,这些通常在 PHP 中称为关联数组,在 Python 中称为字典。
  • 语法不完全相同,但有许多字典扩展尊重键/值对的添加顺序。例如。 seqdict.

标签: python arrays


【解决方案1】:

是的,

a = {"id": 1, "name":"Sesame Street"}

【讨论】:

    【解决方案2】:

    这听起来像使用命名索引的 PHP 数组与 python dict 非常相似:

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

    请参阅http://docs.python.org/tutorial/datastructures.html#dictionaries 了解更多信息。

    【讨论】:

    • 有点太复杂了。我认为海报想要听写
    • 这实际上是一个字典列表。
    【解决方案3】:

    PHP数组其实就是map,相当于Python中的dicts。

    因此,这是 Python 的等价物:

    showlist = [{'id':1, 'name':'Sesaeme Street'}, {'id':2, 'name':'Dora the Explorer'}]

    排序示例:

    from operator import attrgetter
    
    showlist.sort(key=attrgetter('id'))
    

    但是!使用您提供的示例,更简单的数据结构会更好:

    shows = {1: 'Sesame Street', 2:'Dora the Explorer'}
    

    【讨论】:

      【解决方案4】:

      @Unkwntech,

      你想要的可以在刚刚发布的 Python 2.6 中以named tuples 的形式提供。他们允许您这样做:

      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
      

      【讨论】:

      【解决方案5】:

      Python 将列表和字典作为 2 个独立的数据结构。 PHP 将两者合二为一。在这种情况下,您应该使用 dicts。

      【讨论】:

        【解决方案6】:

        我是这样做的:

        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))
        

        我用列表而不是元组做的更复杂,但我覆盖了 setter 和 getter。

        无论如何都允许:

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

        【讨论】:

        • 这是一个很好的例子,说明如何忽略给定编程语言的语义并重新创建自己的解决方案概念。\
        【解决方案7】:

        pandas 库有一个非常简洁的解决方案:Series

        book = pandas.Series( ['Introduction to python', 'Someone', 359, 10],
           index=['Title', 'Author', 'Number of pages', 'Price'])
        print book['Author']
        

        有关更多信息,请查看其文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html

        【讨论】:

          【解决方案8】:

          我想你要问的是关于 python 字典的问题。在那里你可以随意命名你的索引。 例如:

          dictionary = {"name": "python", "age": 12}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-08-05
            • 2015-11-05
            • 1970-01-01
            • 2017-06-20
            • 1970-01-01
            • 2017-07-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多