python 元组、列表、字典、字符串等转换
import json #字典 print(‘dict字典》‘) dict_test = {‘name‘: ‘Zara‘, ‘age‘: 7, ‘class‘: ‘First‘} print(‘初始类型:‘,type(dict_test)) tes=zip(dict_test) print(tes) 9 #字典转换成元组 tu=tuple(dict_test) print(‘字典转换成元组‘,type(tu),tu)12 #字典转换成列表 key=list(dict_test) value=list(dict_test.values()) print(‘字典key转换成列表‘,type(key),key) print(‘字典values转换成列表‘,type(value),value) #字典转换成字符串 str=dict_test.__str__() print(‘字典转换成字符串‘,type(str),str)21 #字典转换成json dict_json=json.dumps(dict_test) print(‘字典转换成json‘,type(dict_json),dict_json) print(‘-----------------------------------------‘) #元组:元组不能转换成字典。 print(‘tuple元组》‘) tuo=(‘name‘, ‘passwd‘, ‘sex‘, ‘phone‘,‘email‘) tup=(1, 2, 3, 4,5) print(‘初始类型:‘,type(tup)) tupList=list(tup) print(‘元组转换成列表‘,type(tupList),tupList) tupStr=tup.__str__() print(‘元组转换成字符串‘,type(tupStr),tupStr) tupStr2=tuo.__str__() print(‘元组转换成字符串2‘,type(tupStr2),tupStr2) tuple_json=json.dumps(tup) print(‘元组转换成json‘,type(tuple_json),tuple_json) #tupDict=dict(tuo,tup) #print(‘元组不能转换成字典‘,type(tupDict),tupDict) print(‘-----------------------------------------‘)42 #列表 print(‘list列表》‘) nums2=[‘name‘, ‘age‘, ‘语文‘, ‘数学‘, ‘英语‘, ‘化学‘, ‘生物‘] nums=[1, 3, 5, 7, 8, 13, 20] print(‘初始类型:‘,type(nums)) list_tuple=tuple(nums) print(‘列表转换成元组‘,type(list_tuple),list_tuple) print(‘初始类型2:‘,type(nums2)) list_dict=dict(zip(nums2,nums))52 #单个列表不能转换成字典,但是2个列表可以用zip(a,b)进行转换成字典 print(‘列表转换成字典‘,type(list_dict),list_dict) list_str=nums.__str__() print(‘列表转换成str‘,type(list_str),list_str) list_json=json.dumps(nums) print(‘list转换成json‘,type(list_json),list_json) print(‘-----------------------------------------‘)59 #字符串 print(‘str字符串》‘) tup=‘test‘ print(‘初始类型:‘,type(tup)) str_dict=tuple(tup) print(‘转换‘,type(str_dict),str_dict) print(‘-----------------------------------------‘)
相关推荐
文山羊 2020-10-31
PYTandFA 2020-09-15
xiesheng 2020-08-06
Tristahong 2020-08-05
柠檬班 2020-07-04
czsay 2020-05-20
Ida 2020-09-16
xiesheng 2020-08-02
oLeiShen 2020-08-01
abdstime 2020-07-29
JamesRayMurphy 2020-07-26
amazingbo 2020-07-21
Greatemperor 2020-07-19
wordmhg 2020-07-16
kekeromer 2020-07-08