将集合转换为字符串,反之亦然

2022-01-17 00:00:00 python python-2.7 string set

问题描述

设置为字符串.很明显:

Set to string. Obvious:

>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> str(s)
'set([1, 2, 3])'

要设置的字符串?也许是这样?

String to set? Maybe like this?

>>> set(map(int,str(s).split('set([')[-1].split('])')[0].split(',')))
set([1, 2, 3])

非常丑陋.有没有更好的方法来序列化/反序列化集合?

Extremely ugly. Is there better way to serialize/deserialize sets?


解决方案

使用 repreval:

>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])

请注意,如果字符串的来源未知,eval 是不安全的,为了更安全的转换,首选 ast.literal_eval:

Note that eval is not safe if the source of string is unknown, prefer ast.literal_eval for safer conversion:

>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])

repr 的帮助:

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

相关文章