Python3 基本数据类型

Number、String、bool、List、Tuple、Set、Dictionary 七种内置类型的定义与特性。

Beginner
Key Points可变类型:list/dict/set;不可变类型:int/float/str/tuple/bool。变量是对象的引用,不是盒子。

标准数据类型

Python 3 has six standard data types — Number, String, List, Tuple, Set, Dictionary — plus bool, making seven in everyday use.

TypeMutableLiteral
int / float / complexNo1, 1.0, 1j
strNo'a', "a"
boolNoTrue, False
listYes[1, 2]
tupleNo(1, 2)
setYes{1, 2}
dictYes{'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.

Python
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)
Output
int float complex
True True
1267650600228229401496703205376
2.0 3.0

String(字符串)

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.

Python
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")
Output
B i Backend
BACKENDWIKI backendwiki
BackendHub
['Backen', 'Wiki']
a-b
BackendWiki has 11 chars

bool(布尔类型)

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.

Python
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)
Output
2 5
False True False True
False True False False
True True

List(列表)

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.

Python
xs = [1, "two", 3.0, [4]]
print(xs, len(xs))

xs[0] = 100
xs.append(5)
print(xs)
print(xs[1:3])
Output
[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.

Python
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)
Output
(1, 2, 3) 3
<class 'int'> tuple
1 3
1 2 3

Set(集合)

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.

Python
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__)
Output
{1, 2, 3} 3
[2, 3] [1, 2, 3, 4] [1]
set

Dictionary(字典)

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.

Python
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)
Output
{'name': 'Tom', 'age': 20} 2
Tom unknown
['age', 'city', 'name']
name = Tom
age = 20
city = Beijing

Friends & Partners