Python3 基本数据类型
type() 与 isinstance()
Python 中一切皆对象,可用 type() 查看类型,用 isinstance(值, 类型) 判断类型,后者还支持元组形式的多类型判断:
x = 100
print(type(x)) # 输出:<class 'int'>
print(isinstance(x, int)) # 输出:True
print(isinstance(x, (int, float))) # 输出:True
标准类型一览
Python3 内置的常用类型如下表:
| 分类 | 类型名 | 字面量示例 |
|---|---|---|
| 数字 | int | 42 |
| 数字 | float | 3.14 |
| 数字 | complex | 1+2j |
| 布尔 | bool | True / False |
| 文本 | str | "hello" |
| 容器 | list | [1, 2, 3] |
| 容器 | tuple | (1, 2, 3) |
| 容器 | dict | {"name": "Tom"} |
| 容器 | set | {1, 2, 3} |
数字与字符串示例
数字分整型、浮点、复数、布尔四类;字符串用引号包裹:
a = 10 # int 整数
b = 3.14 # float 浮点数
c = 1 + 2j # complex 复数
d = True # bool 布尔
s = "你好" # str 字符串
print(type(a), type(b), type(c), type(d), type(s))
# 输出:<class 'int'> <class 'float'> <class 'complex'> <class 'bool'> <class 'str'>
容器类型示例
列表、元组、字典、集合覆盖绝大多数数据组织需求:
lst = [1, 2, 3] # list:有序、可变、可重复
tup = (1, 2, 3) # tuple:有序、不可变
dic = {"name": "Tom", "age": 20} # dict:键值对
st = {1, 2, 3} # set:无序、元素不重复
print(lst[0], tup[1], dic["name"])
# 输出:1 2 Tom
可变与不可变
- 不可变类型:int、float、complex、bool、str、tuple。修改它们的值会新建对象,原对象不变。
- 可变类型:list、dict、set。可以在原对象上原地增删改。
s = "hi"
# s[0] = "H" # 报错:TypeError,str 不支持按索引赋值
lst = [1, 2]
lst.append(3) # 列表支持原地修改
print(lst) # 输出:[1, 2, 3]
空值 None
None 表示"什么都没有",是 NoneType 类型的唯一值,常用作变量初始值或函数的默认返回:
x = None
print(x, type(x)) # 输出:None <class 'NoneType'>
print(x is None) # 输出:True,判断空值必须用 is
数字、字符串负责单值数据,list/tuple/dict/set 负责容器数据;配合 type()/isinstance() 判断类型、牢记可变与不可变之分,即可开始编写复杂程序。