2008-10-07 96 views
20

在PHP我可以说出我的阵列indicies,这样我可以有类似:Python:我可以列出具有指定索引的列表吗?

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

这是可能在Python?

+2

之前有人评论,是的,这些是我最喜欢的节目2。 :) – UnkwnTech 2008-10-07 12:30:28

回答

42

这听起来像使用名为指数的PHP数组非常类似Python字典:

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

更多关于此见http://docs.python.org/tutorial/datastructures.html#dictionaries

+2

位太复杂。我认为这个海报需要字迹 – Rory 2008-10-07 15:54:31

+2

这实际上是一个字典列表。 – 2014-06-22 20:46:33

6

是,

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

PHP数组实际上是地图,它相当于Python中的字典。

因此,这是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'} 
5

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

1

不完全相同的语法,但是有一些字典扩展,其中有关键/值对的添加顺序。例如。 seqdict

14

@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 
+0

当然,这可以模拟老版本的Python(例如:http://users.forthnet.gr/ath/chrisgeorgiou/python/TupleStruct.py) – tzot 2008-10-07 15:53:23

0

Python有列表和字典作为2个独立的数据结构。 PHP混合成一个。在这种情况下你应该使用字典。

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

我做到了,也更多一些列表,而不是元组复杂,但我不得不重写setter方法以及吸气。

不管怎么说,这允许:

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