[英]Convert set to string and vice versa
設置為字符串。 明顯的:
>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> str(s)
'set([1, 2, 3])'
要設置的字符串? 也許像這樣?
>>> set(map(int,str(s).split('set([')[-1].split('])')[0].split(',')))
set([1, 2, 3])
極其丑陋。 有沒有更好的方法來序列化/反序列化集合?
使用repr
和eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
請注意,如果字符串的來源未知,則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])
關於repr
幫助:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
試試這樣,
>>> 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)'
這個問題有點不清楚,因為問題的標題是關於字符串和集合轉換,但最后的問題是如何序列化? !
讓我刷新一下序列化的概念是將對象(包括它所引用的對象)編碼為字節數據流的過程。
如果有興趣序列化,您可以使用:
json.dumps -> serialize
json.loads -> deserialize
如果您的問題更多是關於如何將 set 轉換為 string 和 string to set 然后使用下面的代碼(它在 Python 3 中測試過)
要設置的字符串
set('abca')
設置為字符串
''.join(some_var_set)
例子:
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()
如果您不需要序列化文本是人類可讀的,您可以使用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
結果:
serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])
s = set({1,2,3,4}) # set with int values.
將 set 的每個值轉換為字符串,並將它們連接起來以,
作為分隔符返回一個字符串。
str_val = ', '.join(list(map(str, s)))
str_val
輸出: '1, 2, 3, 4'
用,
作為分隔符分割字符串。 它創建一個列表。 然后將列表轉換為一個集合。
s = set(str_val.split(","))
s
輸出: {' 2', ' 3', ' 4', '1'}
如果集合 1 的長度
>>> s
{'info@montenegroprospects.com'}
>>> list(s)[0]
'info@montenegroprospects.com'
如果集合有多個值
>>> def set2str(l, spe=' - '):
s=''
for i in l:
s += f'{i}{spe}'
return s[:len(s) - len(spe)]
>>> s.add('asfasf')
>>> set2str(s)
'asfasf - info@montenegroprospects.com'
>>> set2str(s,' ') # you can change the spe
'asfasf info@montenegroprospects.com'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.