Python 3 - 变量类型
Python 3 - 变量与数据类型
Section titled “Python 3 - 变量与数据类型”在 Python 中,变量本质上是指向计算机内存中存储的值的名称或标签。创建变量时,你是在将一个名称与特定数据(一个对象)关联起来。
Python 使用动态类型(dynamic typing),这意味着你无需事先显式声明变量的数据类型。类型在赋值时会自动推断。
使用赋值运算符 (=) 将值赋给变量名。名称在左侧,值在右侧。
#!/usr/bin/env python3
count = 100 # Integer assignmentpi_approx = 3.14159 # Floating-point assignmentmessage = "Hello" # String assignmentis_active = True # Boolean assignment
print(count)print(pi_approx)print(message)print(is_active)输出:
1003.14159HelloTruePython 允许同时给多个变量赋相同的值:
x = y = z = 0 # All three variables now refer to the integer 0print(x, y, z)你也可以在一行中给多个变量赋不同的值(序列解包):
a, b, c = 1, 2.5, "world" # a=1, b=2.5, c="world"print(a, b, c)核心内置数据类型
Section titled “核心内置数据类型”Python 有几个核心的内置数据类型:
- 数值类型:
int、float、complex - 序列类型:
str(字符串)、list(列表)、tuple(元组)、range - 映射类型:
dict(字典) - 集合类型:
set、frozenset - 布尔类型:
bool(True和False) - 二进制类型:
bytes、bytearray、memoryview - None 类型:
NoneType(表示值的缺失,只有一个值:None)
让我们更深入地了解最常见的类型。
数值类型 (int、float、complex)
Section titled “数值类型 (int、float、complex)”在“数字”章节中已详细介绍。主要特点:
int:任意精度的整数。float:双精度浮点数(可能有不精确性)。complex:包含实部和虚部的数字(a + bj)。
integer_num = -50float_num = 1.618complex_num = 2 - 3j字符串 (str)
Section titled “字符串 (str)”字符串表示 Unicode 字符序列。它们是不可变的(immutable),创建后无法更改。
使用单引号 ('...')、双引号 ("...") 或三重引号 ('''...''' 或 """...""") 定义。支持索引、切片、连接 (+) 和重复 (*)。
#!/usr/bin/env python3
my_str = 'Hello World!'
print(my_str) # Output: Hello World!print(my_str[0]) # Output: H (first character)print(my_str[6:11]) # Output: World (slicing)print(my_str[6:]) # Output: World! (slice to the end)print(my_str * 2) # Output: Hello World!Hello World!print(my_str + " Goodbye!") # Output: Hello World! Goodbye!
# Immutability example:# my_str[0] = 'J' # TypeError: 'str' object does not support item assignment
# Formatted strings (f-strings - Python 3.6+ are recommended)name = "Alice"age = 30print(f"Name: {name}, Age: {age}") # Output: Name: Alice, Age: 30列表 (list)
Section titled “列表 (list)”列表是有序的、可变的(changeable)项序列,用方括号 [] 括起来。项可以是不同数据类型。
支持索引、切片、连接 (+)、重复 (*),并有用于添加 (append, insert)、删除 (remove, pop)、排序 (sort) 等方法。
#!/usr/bin/env python3
my_list = ['abcd', 786, 2.23, 'john', 70.2, True]tiny_list = [123, 'john']
print(my_list) # Prints complete listprint(my_list[0]) # Prints first element: abcdprint(my_list[1:3]) # Prints elements from index 1 to 2: [786, 2.23]print(my_list[2:]) # Prints elements from index 2 to endprint(tiny_list * 2) # Prints list repeated: [123, 'john', 123, 'john']print(my_list + tiny_list) # Prints concatenated list
# Mutability example:my_list[2] = 'updated'my_list.append(False)print(f"Modified list: {my_list}")元组 (tuple)
Section titled “元组 (tuple)”元组是有序的、不可变的项序列,通常用圆括号 () 括起来。常用于固定集合或需要不可变性的场景(例如,字典的键)。
支持索引、切片、连接 (+)、重复 (*)。创建后不能更改。
#!/usr/bin/env python3
my_tuple = ('abcd', 786, 2.23, 'john', 70.2)tiny_tuple = (123, 'john')
print(my_tuple) # Prints complete tupleprint(my_tuple[0]) # Prints first element: abcdprint(my_tuple[1:3]) # Prints elements from index 1 to 2: (786, 2.23)print(my_tuple[2:]) # Prints elements from index 2 to endprint(tiny_tuple * 2) # Prints tuple repeated: (123, 'john', 123, 'john')print(my_tuple + tiny_tuple) # Prints concatenated tuple
# Immutability example:# my_tuple[2] = 1000 # TypeError: 'tuple' object does not support item assignment字典 (dict)
Section titled “字典 (dict)”字典存储键-值对的无序(Python < 3.7)或按插入顺序(Python 3.7+)集合。用花括号 {} 括起来。
键必须是唯一的且不可变的(可哈希的)。值可以是任何类型。通过键使用方括号 [] 或 .get() 方法访问值。
#!/usr/bin/env python3
my_dict = {}my_dict['one'] = "This is value one"my_dict[2] = "This is value two"
tiny_dict = {'name': 'john', 'code': 6734, 'dept': 'sales'}
print(my_dict['one']) # Access value using key 'one'print(my_dict[2]) # Access value using key 2print(tiny_dict) # Prints complete dictionaryprint(tiny_dict.keys()) # Prints view object of keysprint(tiny_dict.values()) # Prints view object of valuesprint(tiny_dict.items()) # Prints view object of (key, value) pairs
# Modifying dictionarytiny_dict['dept'] = 'marketing'tiny_dict['city'] = 'New York'print(f"Updated tiny_dict: {tiny_dict}")集合 (set、frozenset)
Section titled “集合 (set、frozenset)”set:由唯一的、不可变的项组成的无序集合。用花括号 {} 括起来(但 {} 创建的是空字典,创建空集合要用 set())。适用于成员资格测试和去除重复项。
frozenset:set 的不可变版本。可以用作字典的键或其他集合的元素。
#!/usr/bin/env python3
my_set = {1, 2, 3, 2, 'a'} # Duplicates (2) ignoredprint(f"My set: {my_set}") # Output: {1, 2, 3, 'a'} (order may vary)
empty_set = set()print(f"Empty set: {empty_set}")
# Set operationsset1 = {1, 2, 3}set2 = {3, 4, 5}print(f"Union: {set1 | set2}") # {1, 2, 3, 4, 5}print(f"Intersection: {set1 & set2}") # {3}print(f"Difference: {set1 - set2}") # {1, 2}数据类型转换 (回顾)
Section titled “数据类型转换 (回顾)”使用内置函数如 int()、float()、str()、list()、tuple()、set()、dict() 等在兼容的类型之间进行转换。
示例转换:
| 函数 | 描述 |
|---|---|
int(x [,base]) | 将 x 转换为整数。对于字符串转换,base 是可选的。 |
float(x) | 将 x 转换为浮点数。 |
complex(real [,imag]) | 创建一个复数。 |
str(x) | 将对象 x 转换为字符串。 |
repr(x) | 将对象 x 转换为一个表示其表达式的字符串(通常可由 eval 使用)。 |
eval(str) | 将字符串作为 Python 代码进行求值。警告: 对于不受信任的输入,请极其谨慎使用,存在安全风险。 |
tuple(s) | 将可迭代对象 s 转换为元组。 |
list(s) | 将可迭代对象 s 转换为列表。 |
set(s) | 将可迭代对象 s 转换为集合。 |
dict(d) | 创建一个字典。d 必须是一个由 (key, value) 对组成的可迭代对象。 |
frozenset(s) | 将可迭代对象 s 转换为 frozenset。 |
chr(x) | 将整数 x 转换为其对应的 Unicode 字符。 |
ord(c) | 将单个 Unicode 字符 c 转换为其整数值。 |
hex(x) | 将整数 x 转换为以 “0x” 为前缀的小写十六进制字符串。 |
oct(x) | 将整数 x 转换为以 “0o” 为前缀的八进制字符串。 |
bin(x) | 将整数 x 转换为以 “0b” 为前缀的二进制字符串。 |