您的位置:首页 > 编程语言 > Python开发

python中str(字符串)、list(列表)、tuple(元组)、dict(字典)相互转化关系及字典键-值遍历

2018-02-02 17:19 1071 查看
#!/usr/bin/env python
#coding=utf-8

def main():
strs = "this is a cjh's str"
lst = ['this', 'is', 'a', "cjh's", 'list']
tpl = ('this', 'is', 'a', "cjh's", 'tuple')
dct = {'name': 'cjh', 'age': '25', 'school': 'XDU'}

print '>>>>>>>>>>>>>>>>Print Original Objects'
print strs
print lst
print tpl
print dct

#转化为字符串
print '>>>>>>>>>>>>>>>>List、Tuple、Dictionary into a Str'
print ' '.join(lst)
print ' '.join(tpl)
print ' '.join(dct.iterkeys()),#print默认换行,加逗号可以不换行
print ' '.join(dct.itervalues())

print #空的print表示换行

#转化为list
print '>>>>>>>>>>>>>>>>Str、Tuple、Dictionary into a List'
print list(strs)
print list(tpl)
print list(dct.iterkeys())
print list(dct.itervalues())

#转化为tuple
print '>>>>>>>>>>>>>>>>Str、List、Dictionary into a Tuple'
print tuple(strs)
print tuple(lst)
print tuple(dct.iterkeys())
print tuple(dct.itervalues())

#转化为dict
print '>>>>>>>>>>>>>>>>Str into a Dictionary'
#List、Tuple不能转化为Dictionary
print eval("{'name':'cjh', 'age':25}")

#字典的遍历
print ">>>>>>>>>>>>>>>>Dictionary's Traversal"
#遍历键-值
print ' '.join(('%s:%s' % (key, value)) for key,value in dct.iteritems())#速度最快

#只遍历key
print ' '.join(key for key in dct.iterkeys())

#只遍历values
print ' '.join(value for value in dct.itervalues())

if __name__ == '__main__':
main()


运行结果:

>>>>>>>>>>>>>>>>Print Original Objects

this is a cjh's str

['this', 'is', 'a', "cjh's", 'list']

('this', 'is', 'a', "cjh's", 'tuple')

{'age': '25', 'name': 'cjh', 'school': 'XDU'}

>>>>>>>>>>>>>>>>List、Tuple、Dictionary into a Str

this is a cjh's list

this is a cjh's tuple

age name school 25 cjh XDU

>>>>>>>>>>>>>>>>Str、Tuple、Dictionary into a List

['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'c', 'j', 'h', "'", 's', ' ', 's', 't', 'r']

['this', 'is', 'a', "cjh's", 'tuple']

['age', 'name', 'school']

['25', 'cjh', 'XDU']

>>>>>>>>>>>>>>>>Str、List、Dictionary into a Tuple

('t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'c', 'j', 'h', "'", 's', ' ', 's', 't', 'r')

('this', 'is', 'a', "cjh's", 'list')

('age', 'name', 'school')

('25', 'cjh', 'XDU')

>>>>>>>>>>>>>>>>Str into a Dictionary

{'age': 25, 'name': 'cjh'}

>>>>>>>>>>>>>>>>Dictionary's Traversal

age:25 name:cjh school:XDU

age name school

25 cjh XDU

[Finished in 0.2s]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐