本文介绍了将集合转换为字符串,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置为字符串.很明显:

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.

这篇关于将集合转换为字符串,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:54