在PHP中我可以命名我的数组标记,以便我可能有类似的东西:
$shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'), 1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
这在Python中可行吗?
这听起来像使用命名索引的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中的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: 'Sesaeme Street', 2:'Dora the Explorer'}
@Unkwntech,
刚才发布的Python 2.6以命名元组的形式提供了你想要的东西.他们允许你这样做:
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中的字典.
是,
a = {"id": 1, "name":"Sesame Street"}