# coding=utf-8
__author__ = 'Wang'
a = {'a':1, 'b':2}
###字典键值转化为列表
b = a.keys()
print b
for item in a.keys():
print item, a[item]
####字符串转列表,如果不指定分隔符,spilt函数默认分割成一个,还可以指定分割次数
str_a = "sd,df,dfdf,mdfe.ff,fdf.fdf,sd"
list_b = str_a.split()
list_f = str_a.split(',', 3)
print list_b ###['sd,df,dfdf,mdfe.ff,fdf.fdf,sd']
print list_f ###['sd', 'df', 'dfdf', 'mdfe.ff,fdf.fdf,sd']
####如果需要多个分隔符需要使用正则表达式分割
import re
list_g = re.split('[,.]', str_a)####['sd', 'df', 'dfdf', 'mdfe', 'ff', 'fdf', 'fdf', 'sd']
print list_g
####列表转字典
dir_c = {}
dir_d =dir_c.fromkeys(list_g) ###自动去重####{'fdf': None, 'df': None, 'dfdf': None, 'mdfe': None, 'ff': None, 'sd': None}
print dir_d
list_key = dir_d.keys()####字典的键值是一个列表
for i in list_key:
dir_d[i] = list_g.count(i)
print dir_d #####{'fdf': 2, 'df': 1, 'dfdf': 1, 'mdfe': 1, 'ff': 1, 'sd': 2}
###列表转字符串
src_e = ''.join(list_b) ###sd,df,dfdf,mdfe.ff,fdf.fdf,sd
print src_e
16.python数据类型之间的转化
最新推荐文章于 2022-04-27 20:51:57 发布