Python 将集转换为字符串,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17528374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python convert set to string and vice versa
提问by ov7a
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?
极其丑陋。有没有更好的方法来序列化/反序列化集合?
采纳答案by Ashwini Chaudhary
Use repr
and eval
:
使用repr
和eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
请注意,eval
如果字符串的来源未知,则不安全,更喜欢ast.literal_eval
更安全的转换:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
帮助repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
回答by Adem ?zta?
Try like this,
试试这样,
>>> s = set([1,2,3])
>>> s = list(s)
>>> s
[1, 2, 3]
>>> str = ', '.join(str(e) for e in s)
>>> str = 'set(%s)' % str
>>> str
'set(1, 2, 3)'
回答by Kevin
If you do not need the serialized text to be human readable, you can use pickle
.
如果您不需要序列化文本是人类可读的,您可以使用pickle
.
import pickle
s = set([1,2,3])
serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s
deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s
Result:
结果:
serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])
回答by grepit
The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !
这个问题有点不清楚,因为问题的标题是关于字符串和集合转换,但最后的问题是如何序列化?!
let me refresh the concept of Serializationis the process of encoding an object, including the objects it refers to, as a stream of byte data.
让我刷新一下序列化的概念是将对象(包括它所引用的对象)编码为字节数据流的过程。
If interested to serialize you can use:
如果有兴趣序列化,您可以使用:
json.dumps -> serialize
json.loads -> deserialize
If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)
如果您的问题更多是关于如何将 set 转换为 string 和 string to set 然后使用下面的代码(它在 Python 3 中测试过)
String to Set
要设置的字符串
set('abca')
Set to String
设置为字符串
''.join(some_var_set)
example:
例子:
def test():
some_var_set=set('abca')
print("here is the set:",some_var_set,type(some_var_set))
some_var_string=''.join(some_var_set)
print("here is the string:",some_var_string,type(some_var_string))
test()