1. 程式人生 > >Python 字串、字典、列表、元組、集合之間的相互轉換

Python 字串、字典、列表、元組、集合之間的相互轉換

一、字典
(1)字典轉字串
字典轉字串可以直接使用str函式
dict1 = {'s':12,"er":"io"}
str1 = str(dict1)
結果:
{'s': 12, 'er': 'io'}
利用json進行轉換
import json
data1 = {'b': 789, 'c': 456, 'a': 123}
encode_json = json.dumps(data1)
print type(encode_json), encode_json

結果:
<type 'str'> {"a": 123, "c": 456, "b": 789}


(2)字典轉元組
字典轉元組可以直接使用tuple函式進行轉換,預設轉換的是key,如果要轉換values需要指定
 dict1 = {'key1':'value1','key2':'value2','key3':'value3'}
tuple1 = tuple(dict1)
tuple2 = tuple(dict1.values())

結果:
('key3', 'key2', 'key1')
('value3', 'value2', 'value1')

(3)字典轉列表list
dict1 = {'key1':'value1','key2':'value2','key3':'value3'}
list1 = list(dict1)
list2 = list(dict1.values())

結果:
['key3', 'key2', 'key1']
['value3', 'value2', 'value1']

二、元組
(1)元組轉字串
tuple1 = ("tuple1","tuple2","tuple3")
str1 = str(tuple1)
str2 = str(tuple1[0])
str3 = "".join(tuple1)
str4 = ",".join(tuple1)
str5 = tuple1.__str__()

結果:
"('tuple1', 'tuple2', 'tuple3')"
'tuple1'
'tuple1tuple2tuple3'
'tuple1,tuple2,tuple3'
"('tuple2', 2, 'tuple3')"

注意:在使用join將元組轉換成字串時,元組的元素必須都是字串,不能含有整數
tuple2 = ("tuple2",2,"tuple3")
str2 = ",".join(tuple2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected string, int found

(2)元組轉列表
元組轉列表可以直接使用list函式進行轉換
tuple1 = ('tuple1', 'tuple2', 'tuple3')
tuple2 = ('tuple2', 2, 'tuple3')
list1 = list(tuple1)
list2 = list(tuple2)

結果:
['tuple1', 'tuple2', 'tuple3']
['tuple2', 2, 'tuple3']

三、列表
(1)列表轉字串
列表轉為字串可以直接使用str或者是join
list1 = ["www","baidu","com"]
str1 = str(list1)
str2 = "".join(list1)
str3 = ".".join(list1)
結果:
"['list1', 1, 2, 3, 4, 'list2']"
'www.baidu.com'
注意:
在使用join轉換時,列表元素應該都是字元
含有除字元以外的列表轉字串

list1 = ['www','baidu','com',12,34]
str1 = ".".join(map(str,list1))

結果:
'www.baidu.com.12.34'

(2)列表轉元組
列表轉元組可以直接使用tuple函式
list1 = ['www','baidu','com',12,34]
tuple1 =  ".".join(map(str,list1))
結果:
('www', 'baidu', 'com', 12, 34)

(3)一個列表不可以轉字典,兩個列表轉字典
list1 = ['key1','key2','key3']
list2 = ['1','2','3']
dict(zip(list1,list2))
(4)#巢狀列表轉字典
list3 = [['key1','value1'],['key2','value2'],['key3','value3']]
dict(list3)
(5)列表轉集合(對列表元素去重)
list1 = [2,3,4,5,5,66,2,2]
s = set(list1)
print type(s)
print s
(6)列表、元組轉字串
list2 = ['a', 'a', 'b']
''.join(list2)

tup1 = ('a', 'a', 'b')
''.join(tup1)

四、字串
(1)字串轉元組
str1 = "www.baidu.com"
tuple1 = tuple(str1)

結果:
('w', 'w', 'w', '.', 'b', 'a', 'i', 'd', 'u', '.', 'c', 'o', 'm')
根據指定的字元將字串轉為元組
str1 = "www.baidu.com"
tuple1 = tuple(str1.split('.'))
結果:
('www', 'baidu', 'com')
(2)字串轉列表
str1 = "www.baidu.com"
list1 = list(str1)
結果:
['w', 'w', 'w', '.', 'b', 'a', 'i', 'd', 'u', '.', 'c', 'o', 'm']
根據指定的字元將字串進行拆分為列表
str1 = "www.baidu.com"
list1 = str1.split('.')
結果:
['www', 'baidu', 'com']

(3)字串轉字典
字串轉字典可以使用eval()函式,但是該函式在使用的過程中會遇到一些問題,比如會提示bool型別true、null沒有定義
str2 = "{'key1':'valu1','key2':'value2'}"
dict2 = eval(str2)
結果:
{'key2': 'value2', 'key1': 'valu1'}
使用這個函式會出現一些錯誤
str1 = "{'key1':'value1','key2':true,'key3':null}"
dict1 = eval(str1)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'true' is not defined

出現這種錯誤的原因,是因為該函式無法識別true、null這些,解決方法是:
 global true
 global null

 true = 'true'
 null = 'null'
 dict1 = eval(str1)

 print dict1

結果:
{'key3': 'null', 'key2': 'true', 'key1': 'value1'}

對於多維字典的轉換需要使用另外一個工具json

student = '{"grade":"three","message":{"name":"tom","age":12}}'
result = json.loads(student)
結果:
{u'grade': u'three', u'message': {u'age': 12, u'name': u'tom'}}