python各个数据类型之间的转换

python 基本数据类型

数字
字符串
元组
列表
集合
字典

数字转其他格式
  1. 数字转字符串
    str()
>>> a=123
>>> type(a)
<type 'int'>
>>> b=str(a)
>>> type(b)
<type 'str'>
  1. 数字转列表
    str()–> list()
    需要先转换成字符串,才能转换成列表,又不然会报错。
>>> c=list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> c=list(b)
>>> print c
['1', '2', '3']
  1. 数字转为元组,集合
    str()–> tuple()
    str()–> set()
    需要先转换成字符串,才能转换成列表,又不然会报错。
>>> d=tuple(b)
>>> print d
('1', '2', '3')
>>> e=set(b)
>>> print e
set(['1', '3', '2'])
  1. 数字转为字典,确切说是添加为字典的key或者value。
>>> a={}
>>> a[123]=123
>>> print a
{123: 123}
字符串转为其他格式
  1. 字符串转数字
    内容必须都是数字才可以转换
>>> a='123'
>>> b=int(a)
>>> print b
123
  1. 字符串转元组,集合,列表,如上所述。如果是字符串的格式是元组,集合,列表的表达式,可以使用eval函数
>>> a="('aa','bb')"
>>> b=eval(a)
>>> print b
('aa', 'bb')
>>> type(b)
<type 'tuple'>

  1. 字符串转字典
    如果是非字典格式的字符串,则一般是变为key、或者value。
>>> a={}
>>> a['aa']='aa'
>>> print a
{'aa': 'aa'}

如果是字典格式的字符串,则使用eval函数

>>> a="{'aa':1,'bb':'cc'}"
<type 'str'>
>>> c=eval(a)
>>> type(c)
<type 'dict'>
>>> print c
{'aa': 1, 'bb': 'cc'}
元组转为其他格式
  1. 元组转为数字,没有这说说法,只有读取元组数据。
  2. 元组转字符串
    使用join函数
>>> a=('a','b','c')
>>> b=''.join(a)
>>> print b
abc
>>> type(b)
<type 'str'>
  1. 元组转为列表,集合
    list()
    set()
>>> a=('a','b','c')
>>> b=list(a)
>>> print b
['a', 'b', 'c']
>>> type (b)
<type 'list'>
>>> c=set(a)
>>> print c
set(['a', 'c', 'b'])
>>> type(c)
<type 'set'>
  1. 元组可转字典的key或者value
>>> a={}
>>> a[('a','b','c')]=('a','b','c')
>>> print a
{('a', 'b', 'c'): ('a', 'b', 'c')}
列表转为其他格式

转数字,字符,元组集合列同上述元组
4. 列表不可作为字典的key,但能作为字典value

>>> a={}
>>> a['aa']=['2','3']
>>> print a
{'aa': ['2', '3']}
>>> a[['aa']]=['2','3']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
集合转为其他格式
  1. 集合转数字,没有这说法
  2. 集合转字符串,跟元组列表不同,集合是无序的,不能使用join
>>> a={'1','2','3'}
>>> b=''.join(a)
>>> print b
132
>>> type(b)
<type 'str'>
  1. 集合转为列表,元组 ,注意转后数据排序可能会变
    list()
    tuple()
  2. 集合可转为字典的value,但不能转为key
>>> a={}
>>> a['aa']={'2','3'}
>>> print a
{'aa': set(['3', '2'])}
>>> a[{'aa'}]=['2','3']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
字典转为其他格式
  1. 字典转数字,没有这说法
  2. 字典转字符串
    str()
  3. 字典转元组
    tuple(a) key值转为元组
    tuple(a.values())
>>> a={'aa':1,'bb':'cc'}
>>> str(a)
"{'aa': 1, 'bb': 'cc'}"
>>> b=str(a)
>>> print b
{'aa': 1, 'bb': 'cc'}
>>> c=tuple(a)
>>> print c
('aa', 'bb')
>>> d=tuple(a.values())
>>> print d
(1, 'cc')
  1. 字典转列表,集合
    同上用法,使用list(),set()函数
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值