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

Unk*_*ech 31 python arrays

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

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

这在Python中可行吗?

小智 48

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

shows = [
  {"id": 1, "name": "Sesaeme Street"},
  {"id": 2, "name": "Dora The Explorer"},
]
Run Code Online (Sandbox Code Playgroud)

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

  • 有点太复杂了.我认为这张海报需要说明 (7认同)
  • 这实际上是一个词典列表. (5认同)

Dee*_*tan 21

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'))
Run Code Online (Sandbox Code Playgroud)

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

shows = {1: 'Sesaeme Street', 2:'Dora the Explorer'}
Run Code Online (Sandbox Code Playgroud)


Dan*_*ski 16

@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
Run Code Online (Sandbox Code Playgroud)

  • 命名元组或一般的元组是**不可变**. (16认同)

Ste*_*nik 9

为了协助未来的谷歌搜索,这些通常被称为PHP中的关联数组和Python中的字典.


Lou*_*nco 7

是,

a = {"id": 1, "name":"Sesame Street"}
Run Code Online (Sandbox Code Playgroud)


Sre*_*nth 7

pandas库有一个非常巧妙的解决方案:Series.

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

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