python 基本数据类型
数字
字符串
元组
列表
集合
字典
数字转其他格式
- 数字转字符串
str()
>>> a=123
>>> type(a)
<type 'int'>
>>> b=str(a)
>>> type(b)
<type 'str'>
- 数字转列表
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']
- 数字转为元组,集合
str()–> tuple()
str()–> set()
需要先转换成字符串,才能转换成列表,又不然会报错。
>>> d=tuple(b)
>>> print d
('1', '2', '3')
>>> e=set(b)
>>> print e
set(['1', '3', '2'])
- 数字转为字典,确切说是添加为字典的key或者value。
>>> a={}
>>> a[123]=123
>>> print a
{123: 123}
字符串转为其他格式
- 字符串转数字
内容必须都是数字才可以转换
>>> a='123'
>>> b=int(a)
>>> print b
123
- 字符串转元组,集合,列表,如上所述。如果是字符串的格式是元组,集合,列表的表达式,可以使用eval函数
>>> a="('aa','bb')"
>>> b=eval(a)
>>> print b
('aa', 'bb')
>>> type(b)
<type 'tuple'>
- 字符串转字典
如果是非字典格式的字符串,则一般是变为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'}
元组转为其他格式
- 元组转为数字,没有这说说法,只有读取元组数据。
- 元组转字符串
使用join函数
>>> a=('a','b','c')
>>> b=''.join(a)
>>> print b
abc
>>> type(b)
<type 'str'>
- 元组转为列表,集合
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'>
- 元组可转字典的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'
集合转为其他格式
- 集合转数字,没有这说法
- 集合转字符串,跟元组列表不同,集合是无序的,不能使用join
>>> a={'1','2','3'}
>>> b=''.join(a)
>>> print b
132
>>> type(b)
<type 'str'>
- 集合转为列表,元组 ,注意转后数据排序可能会变
list()
tuple() - 集合可转为字典的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'
字典转为其他格式
- 字典转数字,没有这说法
- 字典转字符串
str() - 字典转元组
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')
- 字典转列表,集合
同上用法,使用list(),set()函数