Python:可以给我一个带有命名索引的列表吗?
在PHP中,我可以命名我的数组索引,这样我可能会有如下内容:Python:可以给我一个带有命名索引的列表吗?,python,arrays,Python,Arrays,在PHP中,我可以命名我的数组索引,这样我可能会有如下内容: $shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'), 1 => Array('id' => 2, 'name' => 'Dora The Explorer')); 这在Python中可能吗?是的 a = {"id": 1, "name":"Sesame Street"} 这听起来像是使用命
$shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
这在Python中可能吗?是的
a = {"id": 1, "name":"Sesame Street"}
这听起来像是使用命名索引的PHP数组与python dict非常相似:
shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
有关这方面的更多信息,请参阅。PHP数组实际上是映射,相当于Python中的dicts 因此,这就是Python的等价物:
showlist=[{'id':1,'name':'sesame Street'},{'id':2,'name':'Dora the Explorer'}]
排序示例:
from operator import attrgetter
showlist.sort(key=attrgetter('id'))
但是!在您提供的示例中,更简单的数据结构会更好:
shows = {1: 'Sesaeme Street', 2:'Dora the Explorer'}
@未知科技
您所需要的在刚刚发布的Python2.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
Python将列表和dict作为两个独立的数据结构。PHP将两者混合在一起。在这种情况下,你应该使用dicts 我是这样做的:
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
熊猫
pandas
库有一个非常简洁的解决方案:Series
book = pandas.Series( ['Introduction to python', 'Someone', 359, 10],
index=['Title', 'Author', 'Number of pages', 'Price'])
print book['Author']
有关更多信息,请查看它的文档:。我认为您要问的是关于python字典的问题。在那里,您可以根据需要命名索引。 例如:
当然,这可以在较旧版本的Python(例如:)中进行模拟。了解2.6很好,现在似乎是升级的时候了。命名元组,或通常的元组,是不可变的。有点太复杂了。我认为海报上的通缉令这实际上是一个字典列表。这是一个很好的例子,说明了如何忽略给定编程语言的语义,重新创建自己的解决方案概念。\n您应该阅读和,特别是其中的一节,该节还介绍了如何帮助未来的谷歌搜索,这些在PHP中通常称为关联数组,和Python中的字典。语法不完全相同,但是有许多字典扩展,它们遵循添加键/值对的顺序。例如。
dictionary = {"name": "python", "age": 12}