Python字符串、列表、字典、元组互转
2016-05-18 19:03
816 查看
#-*-coding:utf-8-*-
#1、字典
dict = {'name': 'Zara', 'age': 7, 'class': 'First'}
#字典转为字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'}
print type(str(dict)), str(dict)
#字典可以转为元组,返回:('age', 'name', 'class')
print tuple(dict)
#字典可以转为元组,返回:(7, 'Zara', 'First')
print tuple(dict.values())
#字典转为列表,返回:['age', 'name', 'class']
print list(dict)
#字典转为列表
print dict.values
#2、元组
tup=(1, 2, 3, 4, 5)
#元组转为字符串,返回:(1, 2, 3, 4, 5)
print tup.__str__()
#元组转为列表,返回:[1, 2, 3, 4, 5]
print list(tup)
#元组不可以转为字典
#3、列表
nums=[1, 3, 5, 7, 8, 13, 20];
#列表转为字符串,返回:[1, 3, 5, 7, 8, 13, 20]
print str(nums)
#列表转为元组,返回:(1, 3, 5, 7, 8, 13, 20)
print tuple(nums)
#列表不可以转为字典
#4、字符串
#字符串转为元组,返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
#字符串转为列表,返回:[1, 2, 3]
print list(eval("(1,2,3)"))
#字符串转为字典,返回:<type 'dict'>
print type(eval("{'name':'ljq', 'age':24}"))
#1、字典
dict = {'name': 'Zara', 'age': 7, 'class': 'First'}
#字典转为字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'}
print type(str(dict)), str(dict)
#字典可以转为元组,返回:('age', 'name', 'class')
print tuple(dict)
#字典可以转为元组,返回:(7, 'Zara', 'First')
print tuple(dict.values())
#字典转为列表,返回:['age', 'name', 'class']
print list(dict)
#字典转为列表
print dict.values
#2、元组
tup=(1, 2, 3, 4, 5)
#元组转为字符串,返回:(1, 2, 3, 4, 5)
print tup.__str__()
#元组转为列表,返回:[1, 2, 3, 4, 5]
print list(tup)
#元组不可以转为字典
#3、列表
nums=[1, 3, 5, 7, 8, 13, 20];
#列表转为字符串,返回:[1, 3, 5, 7, 8, 13, 20]
print str(nums)
#列表转为元组,返回:(1, 3, 5, 7, 8, 13, 20)
print tuple(nums)
#列表不可以转为字典
#4、字符串
#字符串转为元组,返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
#字符串转为列表,返回:[1, 2, 3]
print list(eval("(1,2,3)"))
#字符串转为字典,返回:<type 'dict'>
print type(eval("{'name':'ljq', 'age':24}"))
相关文章推荐
- Python之开发环境的搭建
- Python之简介
- selenium+python笔记2
- python计算时间差的方法
- Python Tricks(七)—— 使用 list 仿真先入先出的队列(FIFOQueue)
- python爬虫爬取百度贴吧的信息
- Python中list,tuple,dict用法
- Python 进阶 —— 魔法函数
- python 正则表达式(regular)
- Python处理Windows事件日志(json)
- ipython for win7 安装
- 《利用Python 进行数据分析》 - 笔记(4)
- Python第三方库整理
- python xml.etree.ElementTree解析xml文件获取节点
- python的list,tuple,dist,set和不可变对象
- 一个python发包的脚本
- Python函数
- Python2与Python3的区别(一):urllib和urllib2与urllib
- Python Tricks(六)—— 删除一个可迭代序列中等于某值的全部元素
- Python中的二维数组(list与numpy.array)