Skip to main content

数据类型

标量类型

i = 10 # int
f = 3.14 # float
s = "hi" # str
b = True # bool
n = None # NoneType

常用转换:int() float() str() bool()

字符串常用操作:

s = "Python"
s.lower() # 'python'
s[0] # 'P'
s[1:4] # 'yth'
"th" in s # True
f"len={len(s)}" # 'len=6'

list(列表,可变、有序)

nums = [1, 2, 3]
nums.append(4)
nums[0] = 10
len(nums)

tuple(元组,不可变、有序)

point = (3, 4)
x, y = point # 解包

dict(字典,键值映射)

user = {"name": "alice", "age": 20}
user["name"]
user.get("email", "") # 缺省值
user["age"] = 21

set(集合,去重、无序)

tags = {"a", "b", "a"} # {'a', 'b'}
tags.add("c")

可变 vs 不可变(直觉)

  • 不可变:int float str tuple bool None
  • 可变:list dict set

把可变对象当默认参数要特别小心(入门「函数与模块」也会再提)。

要点

  1. 先分清「标量」与「容器」
  2. list/dict/set 可变;tuple/str 不可变
  3. 查字典优先考虑 .get(),避免 KeyError