赞
踩
li = [1, 2, 3]
t = tuple(li)
print(t, type(t))
tu = (1, 2, 3)
li = list(tu)
print(li, type(li))
li = [‘人’, ‘生’, ‘苦’, ‘短’]
str1 = ‘’.join(li)
print(str1, type(str1))
str2 = ‘hello python’
li1 = str2.split(’ ')
print(li1, type(li1))
list1 = [‘name’, ‘age’, ‘sex’]
list2 = [‘张三’, 18, ‘男’]
dict = {}
for i in range(len(list1)):
dict[list1[i]] = list2[i]
print(dict, type(dict))
list1 = [‘name’, ‘age’, ‘sex’]
list2 = [‘张三’, 18, ‘男’]
d = dict(zip(list1, list2))
print(d)
dict = {‘name’: ‘张三’, ‘age’: 18, ‘sex’: ‘男’}
keys = list(dict.keys())
values = list(dict.values())
print(keys, type(keys))
print(values, type(values))
4.嵌套列表转字典
list3 = [[‘key1’,‘value1’],[‘key2’,‘value2’],[‘key3’,‘value3’]]
print(dict(list3))
5. 列表与集合转换
list1 = [1, 3, 4, 3, 2, 1]
s1 = set(list1)
print(s1, type(s1))
list2 = list(s1.intersection(s1))
print(list2, type(list2))
list = []
a = ‘人生苦短’
list.append(a)
print(list)
b = tuple(list)
print(b, type(b))
7.元组和字典转换
dict = {‘name’: ‘xiaoming’, ‘age’: 18}
tup = tuple(dict)
print(tup) # 只转换了key
tup2 = tuple(dict.values())
print(tup2)
8.字典和字符串转换
dic1 = {‘a’: 1, ‘b’: 2}
str1 = str(dic1)
dic2 = eval(“{‘name’:‘xiaoming’, ‘age’:18}”)
print(dic2, type(dic2))
9.字符串和集合转换
str1 = ‘hello’
s1 = set(str1)
print(s1, type(s1))
10.字典key和value值转换
dic1 = {‘a’: 1, ‘b’: 2, ‘c’: 3}
dic2 = {value: key for key, value in dic1.items()}
print(dic2)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。