python 列表责蝠,元組党巾,字典,集合霜医,字符串相互轉(zhuǎn)換
1. 列表與元組的互換-------------------------------------------------
1.1將列表轉(zhuǎn)化為元組
li = [1, 2, 3]
t = tuple(li)
print(t, type(t))
1.2 將元組轉(zhuǎn)換成列表
del list #先清除list緩存
tu = (1, 2, 3)
li = list(tu)
print(li, type(li))
2. 列表與字符串的互換-----------------------------------------------
2.1列表轉(zhuǎn)換成字符串
li = ['人', '生', '苦', '短']
str1 = ''.join(li)
print(str1, type(str1))
2.2字符串轉(zhuǎn)換成列表
str2 = 'hello python'
li1 = str2.split(' ')
print(li1, type(li1))
3. 列表與字典轉(zhuǎn)換----------------------------------------------------
3.1列表轉(zhuǎn)字典方式一
list1 = ['name', 'age', 'sex']
list2 = ['張三', 18, '男']
dict = {}
for i in range(len(list1)):
dict[list1[i]] = list2[i]
print(dict, type(dict))
3.2列表轉(zhuǎn)字典方式二:使用內(nèi)置函數(shù)zip
del dict#清除緩存
list1 = ['name', 'age', 'sex']
list2 = ['張三', 18, '男']
d = dict(zip(list1, list2))
print(d)
3.3字典轉(zhuǎn)換成列表
dict = {'name': '張三', 'age': 18, 'sex': '男'}
keys = list(dict.keys())
values = list(dict.values())
print(keys, type(keys))
print(values, type(values))
3.4嵌套列表轉(zhuǎn)字典
list3 = [['key1','value1'],['key2','value2'],['key3','value3']]
print(dict(list3))
5.列表與集合轉(zhuǎn)換------------------------------------------------------------
5.1列表轉(zhuǎn)集合
list1 = [1, 3, 4, 3, 2, 1]
s1 = set(list1)
print(s1, type(s1))
輸出結(jié)果:{1, 2, 3, 4} <class 'set'>
5.2集合轉(zhuǎn)列表
list1 = [1, 3, 4, 3, 2, 1]
s1 = set(list1)
list2 = list(s1.intersection(s1))
print(list2, type(list2))
6.元組和字符串轉(zhuǎn)換--------------------------------------------------------------------
6.1元組轉(zhuǎn)換成字符串和列表方法一樣
6.2字符串轉(zhuǎn)換成元組齿拂,需要將字符串轉(zhuǎn)換成列表,在利用列表轉(zhuǎn)成元組
list = []
a = '人生苦短'
list.append(a)
print(list)
b = tuple(list)
print(b, type(b))
7.元組和字典轉(zhuǎn)換---------------------------------------------------------------------
7.1字典轉(zhuǎn)元組
dict = {'name': 'xiaoming', 'age': 18}
tup = tuple(dict)
print(tup) # 只轉(zhuǎn)換了key
tup2 = tuple(dict.values())
print(tup2)
7.2元組不能轉(zhuǎn)成字典
8.字典和字符串轉(zhuǎn)換--------------------------------------------------------
8.1字典轉(zhuǎn)換為字符串
dic1 = {'a': 1, 'b': 2}
str1 = str(dic1)
8.2字符串轉(zhuǎn)字典
dic2 = eval("{'name':'xiaoming', 'age':18}")
print(dic2, type(dic2))
9.字符串和集合轉(zhuǎn)換
9.1字符串轉(zhuǎn)集合
str1 = 'hello'
s1 = set(str1)
print(s1, type(s1))
10.字典key和value值轉(zhuǎn)換
dic1 = {'a': 1, 'b': 2, 'c': 3}
dic2 = {value: key for key, value in dic1.items()}
print(dic2)