字符串&列表&元组&字典之间互转

laohyx 2020-05-19

#!/usr/bin/env/python
#-*-coding:utf-8-*-

#Author:LingChongShi   #查看源码Ctrl+左键

#数据类型之间的转换
Str=‘www.baidu.com‘
‘‘‘一、str--->list‘‘‘
print(‘str-->list:‘,Str.split(‘.‘),type(Str.split()))
‘‘‘二、str--->tuple‘‘‘
print(‘str--->tuple‘,Str.partition(‘.‘),type(Str.partition(‘.‘)))
‘‘‘三、str--->dict‘‘‘
Str=‘{"name":"xiaoshao","age":10,"address":"xian"}‘
print(‘str--->dict:‘,eval(Str),type(eval(Str)))

List= [‘www‘, ‘baidu‘, ‘com‘]
‘‘‘一、list--->str‘‘‘
print(‘list--->str:‘,‘.‘.join(List),type(‘.‘.join(List)))
‘‘‘二、list--->tuple‘‘‘
print(‘list--->tuple:‘,tuple(List),type(tuple(List)))
‘‘‘三、list--->dict‘‘‘
print(‘list--->dict:‘,dict(enumerate(List)),type(dict(enumerate(List))))
List1= [1,2,3]
print(‘list--->dict:‘,dict(zip(List,List1)),type(dict(zip(List,List1))))
List2= [[‘www‘,1],[‘baidu‘,2],[‘com‘,3]]
print(‘list--->dict:‘,dict(List2),type(dict(List2)))

Tuple=(‘www‘, ‘baidu‘, ‘com‘)
‘‘‘一、tuple--->str‘‘‘
print(‘tuple--->str:‘,‘.‘.join(Tuple),type(‘.‘.join(Tuple)))
‘‘‘二、tuple--->list‘‘‘
print(‘tuple--->list:‘,list(Tuple),type(list(Tuple)))
‘‘‘三、tuple--->dict‘‘‘
print(‘tuple--->dict:‘,dict(enumerate(Tuple)),type(dict(enumerate(Tuple))))

Dict={‘name‘:‘xiaoshao‘,‘age‘:10,‘address‘:‘xian‘}
‘‘‘一、dict--->str‘‘‘
print(‘dict--->str:‘,str(Dict),type(str(Dict)))
‘‘‘二、dict--->list‘‘‘
print(‘dict--->list:‘,list(Dict.keys()),type(list(Dict.keys())))
print(‘dict--->list:‘,list(Dict.values()),type(list(Dict.values())))
‘‘‘三、dict--->tuple‘‘‘
print(‘dict--->tuple:‘,tuple(Dict.keys()),type(tuple(Dict.keys())))
print(‘dict--->tuple:‘,tuple(Dict.values()),type(tuple(Dict.values())))

相关推荐