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

Posted forforever

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串&列表&元组&字典之间互转相关的知识,希望对你有一定的参考价值。

#!/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())))

 

以上是关于字符串&列表&元组&字典之间互转的主要内容,如果未能解决你的问题,请参考以下文章

Python的列表&元组&字典&集合

python之列表/元组/字典/字符串

元组&字典

python 之 列表list && 元组tuple

json & pickle

python基础之序列类型的方法——列表&元组