数字、字符串与列表

翻译整理自 Python Tutorial - An Informal Introduction。

1. 数字 Numbers

Python 内置三种数值类型:

2 + 2            # 4,int
50 - 5 * 6       # 20
8 / 5            # 1.6,float
17 // 3          # 5,整除
17 % 3           # 2,取余
2 ** 7           # 128,幂
int(3.7)         # 3
float(3)         # 3.0

浮点数

4 / 3            # 1.3333333333333333
0.1 + 0.2        # 0.30000000000000004(浮点误差)
round(2.5)       # 2(银行家舍入)

需要精确十进制运算用 decimal:

from decimal import Decimal
Decimal("0.1") + Decimal("0.2")  # Decimal('0.3')

复数

3 + 1j           # 复数
z = 2 + 3j
z.real           # 2.0
z.imag           # 3.0

2. 字符串 Strings

字符串字面量:

single = '单引号'
double = "双引号"
triple = """三引号
可换行"""
raw   = r"C:\new\folder"   # 原始字符串
fstr  = f"{single}长度{len(single)}"

操作

s = "Hello"
s[0]            # 'H'
s[-1]           # 'o'
s[1:4]          # 'ell'
len(s)          # 5
"Go" + "lang"   # 'Golang'
"a" * 3         # 'aaa'
"Py" in s       # False

字符串方法

"hello".upper()              # 'HELLO'
"  x  ".strip()              # 'x'
"a,b,c".split(",")          # ['a', 'b', 'c']
",".join(["a","b","c"])     # 'a,b,c'
"name: {0}".format("Go")    # 'name: Go'
"%s=%d" % ("x", 1)          # 'x=1'
"123".isdigit()             # True

字符串不可变,所有方法都返回新字符串。

3. 列表 Lists

列表是可变序列:

nums = [1, 2, 3, 4, 5]
nums[0]            # 1
nums[-1]           # 5
nums[1:3]          # [2, 3]
nums[2:]           # [3, 4, 5]
len(nums)          # 5

修改

nums[0] = 10
nums.append(6)            # [10, 2, 3, 4, 5, 6]
nums.insert(1, 99)        # [10, 99, 2, ...]
nums.extend([7, 8])
nums.remove(99)           # 按值删除
popped = nums.pop()       # 弹出末尾
del nums[0]               # 按索引删

嵌套

matrix = [[1, 2], [3, 4]]
matrix[1][0]  # 3

列表推导

squares = [x * x for x in range(10)]
evens   = [x for x in range(10) if x % 2 == 0]
pairs   = [(x, y) for x in range(3) for y in range(3) if x != y]

小结

数字、字符串、列表是 Python 三大基础数据。下一章学习流程控制。