Python3 基本数据类型
Number、String、bool、List、Tuple、Set、Dictionary 七种内置类型的定义与特性。
标准数据类型
Python 3 has six standard data types — Number, String, List, Tuple, Set, Dictionary — plus bool, making seven in everyday use.
| Type | Mutable | Literal |
|---|---|---|
| int / float / complex | No | 1, 1.0, 1j |
| str | No | 'a', "a" |
| bool | No | True, False |
| list | Yes | [1, 2] |
| tuple | No | (1, 2) |
| set | Yes | {1, 2} |
| dict | Yes | {'a': 1} |
Number(数字)
int is an arbitrary-precision integer (never overflows), float is double precision, complex holds complex numbers. type() reports the class, isinstance() tests membership and also accepts subclasses.
a, b, c = 10, 3.14, 2 + 3j
print(type(a).__name__, type(b).__name__, type(c).__name__)
print(isinstance(a, int), isinstance(True, int))
print(2 ** 100)
print(c.real, c.imag)int float complex
True True
1267650600228229401496703205376
2.0 3.0String(字符串)
A string is an immutable sequence supporting indexing, slicing and many methods. + concatenates, * repeats, in tests substring, and the f prefix interpolates. Slices include the start and exclude the stop.
s = "BackendWiki"
print(s[0], s[-1], s[0:7])
print(s.upper(), s.lower())
print(s.replace("Wiki", "Hub"))
print(s.split("d"))
print("-".join(["a", "b"]))
print(f"{s} has {len(s)} chars")B i Backend
BACKENDWIKI backendwiki
BackendHub
['Backen', 'Wiki']
a-b
BackendWiki has 11 charsbool(布尔类型)
bool has only True and False and subclasses int (True == 1). Empty values, zero and empty containers are falsy in conditions; everything else is truthy.
print(True + True, True * 5)
print(bool(0), bool(1), bool(""), bool("0"))
print(bool([]), bool([0]), bool({}), bool(None))
print(1 == True, 0 == False)2 5
False True False True
False True False False
True TrueList(列表)
A list is a mutable ordered sequence written with brackets; elements may be of mixed types. It supports update, append and delete, and is the most-used container in Python.
xs = [1, "two", 3.0, [4]]
print(xs, len(xs))
xs[0] = 100
xs.append(5)
print(xs)
print(xs[1:3])[1, 'two', 3.0, [4]] 4
[100, 'two', 3.0, [4], 5]
['two', 3.0]Tuple(元组)
Tuples are defined by commas and are immutable, so they can serve as dict keys or set members. A one-element tuple needs a trailing comma: (1,) is a tuple, (1) is just an int.
t = (1, 2, 3)
print(t, len(t))
print(type((1)), type((1,)).__name__)
print(t[0], t[-1])
a, b, c = t
print(a, b, c)(1, 2, 3) 3
<class 'int'> tuple
1 3
1 2 3Set(集合)
A set is unordered with unique elements, built with {} or set(). It shines for deduplication and set algebra; members must be hashable, so lists are out.
s = {1, 2, 2, 3}
print(s, len(s))
a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a & b), sorted(a | b), sorted(a - b))
print(type(set()).__name__){1, 2, 3} 3
[2, 3] [1, 2, 3, 4] [1]
setDictionary(字典)
A dict maps unique hashable keys to values and preserves insertion order since 3.7. d[k] raises KeyError when missing; get(k, default) is safer.
d = {'name': 'Tom', 'age': 20}
print(d, len(d))
print(d['name'], d.get('city', 'unknown'))
d['city'] = 'Beijing'
print(sorted(d))
for k, v in d.items():
print(k, '=', v){'name': 'Tom', 'age': 20} 2
Tom unknown
['age', 'city', 'name']
name = Tom
age = 20
city = Beijing标准数据类型
Python 3 有六种标准数据类型:Number(数字)、String(字符串)、List(列表)、Tuple(元组)、Set(集合)、Dictionary(字典),加上 bool 共七种常用类型。
| 类型 | 可变 | 字面量 |
|---|---|---|
| 整数 / 浮点 / 复数 | 否 | 1、1.0、1j |
| 字符串 | 否 | 'a'、"a" |
| 布尔 | 否 | True、False |
| 列表 | 是 | [1, 2] |
| 元组 | 否 | (1, 2) |
| 集合 | 是 | {1, 2} |
| 字典 | 是 | {'a': 1} |
Number(数字)
int 是任意精度整数(不会溢出)、float 是双精度浮点、complex 是复数。type() 看类型,isinstance() 判断归属,后者对子类也成立。
a, b, c = 10, 3.14, 2 + 3j
print(type(a).__name__, type(b).__name__, type(c).__name__)
print(isinstance(a, int), isinstance(True, int))
print(2 ** 100)
print(c.real, c.imag)int float complex
True True
1267650600228229401496703205376
2.0 3.0String(字符串)
字符串是不可变序列,支持下标、切片和大量方法。+ 拼接、* 重复、in 判断子串;f'' 前缀做插值。切片同样含头不含尾。
s = "BackendWiki"
print(s[0], s[-1], s[0:7])
print(s.upper(), s.lower())
print(s.replace("Wiki", "Hub"))
print(s.split("d"))
print("-".join(["a", "b"]))
print(f"{s} has {len(s)} chars")B i Backend
BACKENDWIKI backendwiki
BackendHub
['Backen', 'Wiki']
a-b
BackendWiki has 11 charsbool(布尔类型)
bool 只有 True 和 False,且是 int 的子类(True == 1)。空值、零、空容器在条件判断中都是假值,其他为真。
print(True + True, True * 5)
print(bool(0), bool(1), bool(""), bool("0"))
print(bool([]), bool([0]), bool({}), bool(None))
print(1 == True, 0 == False)2 5
False True False True
False True False False
True TrueList(列表)
列表是可变有序序列,用方括号定义,元素类型可混合。可以修改、追加、删除,是 Python 里最常用的容器。
xs = [1, "two", 3.0, [4]]
print(xs, len(xs))
xs[0] = 100
xs.append(5)
print(xs)
print(xs[1:3])[1, 'two', 3.0, [4]] 4
[100, 'two', 3.0, [4], 5]
['two', 3.0]Tuple(元组)
元组用逗号定义,不可变,因此可作为字典键或放进集合。单元素元组必须带逗号:(1,) 是元组,(1) 只是整数。
t = (1, 2, 3)
print(t, len(t))
print(type((1)), type((1,)).__name__)
print(t[0], t[-1])
a, b, c = t
print(a, b, c)(1, 2, 3) 3
<class 'int'> tuple
1 3
1 2 3Set(集合)
集合无序、元素唯一,用 {} 或 set() 创建。常用于去重和集合运算;元素必须可哈希,所以不能放列表。
s = {1, 2, 2, 3}
print(s, len(s))
a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a & b), sorted(a | b), sorted(a - b))
print(type(set()).__name__){1, 2, 3} 3
[2, 3] [1, 2, 3, 4] [1]
setDictionary(字典)
字典是键值对映射,键唯一且可哈希,3.7 起保持插入顺序。用 d[k] 取值(键不存在会抛 KeyError),get(k, default) 更安全。
d = {'name': 'Tom', 'age': 20}
print(d, len(d))
print(d['name'], d.get('city', 'unknown'))
d['city'] = 'Beijing'
print(sorted(d))
for k, v in d.items():
print(k, '=', v){'name': 'Tom', 'age': 20} 2
Tom unknown
['age', 'city', 'name']
name = Tom
age = 20
city = Beijing