2013-07-08 13 views
11

Imposta su stringa. Ovvio:Converti Python impostato su stringa e viceversa

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

Stringa da impostare? Forse così?

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

Estremamente brutto. C'è un modo migliore per serializzare/deserializzare i set?

risposta

10

Usa repr e eval:

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

Nota che eval non è sicuro se la fonte di stringa è sconosciuta, preferiscono ast.literal_eval per la conversione più sicuro:

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

aiuto su repr:

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

ast.literal_eval, non eval – georg

+0

@ thg435 aggiunto che pure. –

5

Prova in questo modo,

>>> 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)' 
+2

Non penso che questo sia ciò che l'OP vuole fare. – arshajii

+0

La domanda è: * Conversione in Python impostata su ** stringa ** e viceversa *. –

2

Se non è necessario il testo serializzato per essere leggibile, è possibile utilizzare 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 

Risultato:

serialized: 
c__builtin__ 
set 
p0 
((lp1 
I1 
aI2 
aI3 
atp2 
Rp3 
. 
deserialized: 
set([1, 2, 3]) 
Problemi correlati