Python:我可以有一个带有命名索引的列表吗?

时间:2008-10-07 12:25:25

标签: python arrays

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

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

这在Python中是否可行?

11 个答案:

答案 0 :(得分:46)

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

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

有关详情,请参阅http://docs.python.org/tutorial/datastructures.html#dictionaries

答案 1 :(得分:21)

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

BUT!通过您提供的示例,更简单的数据结构会更好:

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

答案 2 :(得分:15)

@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

答案 3 :(得分:8)

为了协助未来的Google搜索,这些通常在PHP中称为关联数组,在Python中称为字典。

答案 4 :(得分:6)

是,

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

答案 5 :(得分:2)

您应该阅读python tutorial和esp。关于datastructures的部分也涵盖了dictionaries.

答案 6 :(得分:2)

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

答案 7 :(得分:1)

语法不完全相同,但是有许多字典扩展,它们遵循键/值对的添加顺序。例如。 seqdict

答案 8 :(得分:0)

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

答案 9 :(得分:0)

我认为您要问的是关于python字典的信息。您可以根据需要命名索引。 例如:

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

答案 10 :(得分:-4)

我是这样做的:

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

我用list而不是tuple做了一点复杂,但是我已经覆盖了setter和getter。

无论如何这允许:

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