Python 3 中有六个标准的数据类型:
目录
1. Numbers(数字)
Python 3 支持 int(整型)、float(浮点型)、bool(布尔型)、complex(复数)。
>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'><class 'float'><class 'bool'><class 'complex'>
数值运算:
>>> 5 + 4 # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7 # 乘法
21
>>> 2 / 4 # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余
2
>>> 2 ** 5 # 乘方
32
2. String(字符串)
Python 中的字符串 str 用单引号(' ')或双引号 (" ") 括起来,同时使用反斜杠 (\) 转义特殊字符。
>>> s = 'Yes,he doesn\'t'
>>> print(s, type(s), len(s))
Yes,he doesn't <class 'str'> 14
3. List(列表)
>>> a = ['him', 25, 100, 'her']
>>> print(a)
['him', 25, 100, 'her']
4. Tuple(元组)
>>> a = (1991, 2014, 'physics', 'math')
>>> print(a, type(a), len(a))
(1991, 2014, 'physics', 'math') <class 'tuple'> 4
5. Sets(集合)
>>> student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
>>> print(student) # 重复的元素被自动去掉
{'Jim', 'Jack', 'Mary', 'Tom', 'Rose'}
>>> 'Rose' in student # membership testing(成员测试)
True
>>> # set可以进行集合运算
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a', 'b', 'c', 'd', 'r'}
>>> a - b # a和b的差集
{'b', 'd', 'r'}
>>> a | b # a和b的并集
{'l', 'm', 'a', 'b', 'c', 'd', 'z', 'r'}
>>> a & b # a和b的交集
{'a', 'c'}
>>> a ^ b # a和b中不同时存在的元素
{'l', 'm', 'b', 'd', 'z', 'r'}
6. Dictionaries(字典)
>>> dic = {} # 创建空字典
>>> tel = {'Jack':1557, 'Tom':1320, 'Rose':1886}
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Rose': 1886}
>>> tel['Jack'] # 主要的操作:通过key查询
1557
>>> del tel['Rose'] # 删除一个键值对
>>> tel['Mary'] = 4127 # 添加一个键值对
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Mary': 4127}
>>> list(tel.keys()) # 返回所有key组成的list
['Tom', 'Jack', 'Mary']
>>> sorted(tel.keys()) # 按key排序
['Jack', 'Mary', 'Tom']
>>> 'Tom' in tel # 成员测试
True
>>> 'Mary' not in tel # 成员测试
False