简体   繁体   English

表示python中的数据结构

[英]Representing data-structure in python

What's the best way to represent this data-structure in python: 在python中表示此数据结构的最佳方法是什么:

[{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]

It's not json, it's something else, sorry for my stupidity, I'm searching various python tutorials, but can't figure out if it's some structure that can be easily loaded like numpy.load or json.loads, because when I try validating that structure as JSON, it says invalid json... 它不是json,是另一回事,对不起我,我正在搜索各种python教程,但无法确定它是否可以像numpy.load或json.loads这样容易加载的结构,因为当我尝试验证时该结构为JSON,表示无效json ...

What you have there is a list of dictionaries. 您所拥有的是字典列表。

myList = []

dict1 = {'x': 230, 'y': 50}
dict2 = {'x': 350, 'y': 50}
dict3 = {'x': 410, 'y': 50}

myList.append(dict1)
myList.append(dict2)
myList.append(dict3)

You have a list of three dictionaries (mappings of keys to values) and it works like this: 您有三个字典的列表(值的键映射),其工作方式如下:

>>> dicts = [{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]
>>> dicts[0]
{'x': 230, 'y': 50}
>>> dicts[0]['x']
230
>>> dicts[2]['y']
50

Since all the dictionaries share the same keys ( 'x' and 'y' ) in your example you can interpret them as records . 由于在您的示例中所有词典共享相同的键( 'x''y' ),因此您可以将它们解释为记录

A neat way to represent these records is with a pandas.DataFrame , which has a table-like printout. 表示这些记录的一种好方法是使用pandas.DataFrame ,它具有类似表格的打印输出。

>>> import pandas as pd
>>> pd.DataFrame(dicts)
     x   y
0  230  50
1  350  50
2  410  50

If you have a string 如果你有一个字符串

>>> s = "[{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]"

you can evaluate it safely with ast.literal_eval . 您可以使用ast.literal_eval安全地对其进行评估。

>>> from ast import literal_eval
>>> literal_eval(s)
[{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM