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

2024-06-12 18:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在PHP中,我可以命名我的数组索引,这样我就可以得到如下内容:

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

这在Python中可能吗?


Tags: thenameidstreet内容数组array命名
3条回答

@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

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

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

请参阅http://docs.python.org/tutorial/datastructures.html#dictionaries了解有关此的详细信息。

PHP数组实际上是映射,相当于Python中的dict。

因此,这相当于Python:

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

排序示例:

from operator import attrgetter

showlist.sort(key=attrgetter('id'))

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

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

相关问题 更多 >