在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.
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)
该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 。
| 归档时间: |
|
| 查看次数: |
67590 次 |
| 最近记录: |