简体   繁体   English

要列出的namedtuple的字符串

[英]String of namedtuples to list

How would I convert string of namedtuples to a list? 如何将namedtuple的字符串转换为列表?

The problem is I have to store a list of namedtuples in a column in SQLite, which (obviously) doesn't support the format. 问题是我必须在SQLite的列中存储一个namedtuple列表,(显然)它不支持该格式。 I thought of just converting it into a string. 我想到了只是将其转换为字符串。 However, since my tuple is a namedtuple, I don't know how to go from the string to list again. 但是,由于我的元组是一个namedtuple,所以我不知道如何从字符串重新列出。

>>> Point = namedtuple("Point", "x y", verbose = False)
>>> p = Point(3, 5)
>>> points = []
>>> points.append(Point(4, 7))
>>> points.append(Point(8, 9))
>>> points.append(p)
>>> p.x
3
>>> print points
[Point(x=4, y=7), Point(x=8, y=9), Point(x=3, y=5)]

My list of named tuples is something like this^^^^, but it has 6 arguments instead of the 2 shown above. 我的命名元组列表类似这样^^^^,但是它有6个参数,而不是上面显示的2个。 Edit - the arguments are booleans, ints, and strings. 编辑-参数为布尔值,整数和字符串。

I tried mapping, but i got the following error: 我尝试映射,但出现以下错误:

>>> string = str(points)
>>> l = string.strip("[]")
>>> p = map(Point._make, l.split(", "))

Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
p = map(Point._make, l.split(", "))
File "<string>", line 17, in _make
TypeError: Expected 2 arguments, got 9

I'm open to other simpler ways to do this. 我愿意接受其他更简单的方法来做到这一点。

I'd recommend you to use modules like pickle that allow to to store python objects in files. 我建议您使用允许将python对象存储在文件中的模块,例如pickle

By the way I am not sure if namedtuple will work with pickle , if that's the case and source of the data is not unknown then you can also use eval with repr : 顺便说一下,我不确定namedtuple是否可以与pickle ,如果是这种情况,并且数据来源不明,那么您也可以将evalrepr一起使用:

help on repr : 帮助repr

>>> print repr.__doc__
repr(object) -> string

Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.

Example: 例:

>>> repr(points)
'[Point(x=4, y=7), Point(x=8, y=9), Point(x=3, y=5)]'
>>> eval(repr(points))
[Point(x=4, y=7), Point(x=8, y=9), Point(x=3, y=5)]

Ultimately, how to do this may be a matter of taste. 最终,如何做到这一点可能取决于品味。

JSON JSON格式

Json can be a good use because, unlike pickle, it is usable beyond python. Json可以很好地使用,因为与pickle不同,它可以在python之外使用。 Your object is serialized in a widely supported, easily repurposed format. 您的对象以广泛支持的,易于重新使用的格式序列化。

>>> import json  # simple json is better bit I didn't want to force an install
>>> from collections import namedtuple
>>> Point = namedtuple("Point", "x y", verbose = False)
>>> p = Point(3,4)
>>> json.dumps(p._asdict())
'{"x": 3, "y": 4}'
>>> s = json.dumps(p._asdict())
>>> json.loads(s)  # not there yet cause thisis a dict
{u'y': 4, u'x': 3}   # but it is a dict that can create a Point
>>> Point(**json.loads(s))
Point(x=3, y=4)    

Pickle 泡菜

pickle will not work unless you define a attribute state (see __getstate__ in the docs ). 除非您定义属性状态(请参阅__getstate__ 中的 __getstate__ 否则pickle不会起作用。 This is "Nicer" in the load phase, following from above: 这是加载阶段中的“ Nicer”,从上至下:

import pickle

# Point.__getstate__=lambda self: self._asdict() # not needed as per @simon's comment thx simon
>>> pickle.dumps(p)
"ccopy_reg\n_reconstructor\np0\n(c__main__\nPoint\np1\nc__builtin__\ntuple\np2\n(I3\nI4\ntp3\ntp4\nRp5\nccollections\nOrderedDict\np6\n((lp7\n(lp8\nS'x'\np9\naI3\naa(lp10\nS'y'\np11\naI4\naatp12\nRp13\nb."
s = pickle.dumps(p)
>>> pickle.loads(s)
Point(x=3, y=4)

eval 评估

I would discourage any use of eval or exec. 我不鼓励使用eval或exec。 If you do go down that route check out ast.literal_eval() and checkout some of the SO related answers like safety of python eval 如果您确实走了那条路线,请检查ast.literal_eval()并检查一些与SO相关的答案,例如python eval的安全性

Based on Phil Cooper answer, you can store your objects in json format: 根据Phil Cooper的答案,您可以将对象存储为json格式:

>>> import json

>>> points_str = json.dumps([x._asdict() for x in points])
[{"x": 4, "y": 7}, {"x": 8, "y": 9}, {"x": 1, "y": 2}]

>>> points2 = [Point(**x) for x in json.loads(points_str)]
[Point(x=4, y=7), Point(x=8, y=9), Point(x=1, y=2)]

another strange way to do it is to use exec : 另一个奇怪的方法是使用exec

>>> points_str = repr(points)
'[Point(x=4, y=7), Point(x=8, y=9), Point(x=1, y=2)]'

>>> exec "points2 = %s" % points
>>> points2
[Point(x=4, y=7), Point(x=8, y=9), Point(x=1, y=2)]

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

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