Appearance
Python 基础面试题
1. Python 数据类型
问题:Python 有哪些基本数据类型?它们之间有什么区别?
答案:
基本数据类型:
python
# 1. 数字(Number)
# 整数
a = 10
b = -5
# 浮点数
c = 3.14
d = 2.5e2 # 250.0
# 复数
e = 3 + 4j
# 2. 字符串(String)
s = "Hello, Python!"
multiline = """多行
字符串"""
# 3. 列表(List)
my_list = [1, 2, 3, "a", "b"]
my_list.append(4) # 可变
# 4. 元组(Tuple)
my_tuple = (1, 2, 3) # 不可变
# 5. 字典(Dictionary)
my_dict = {"name": "Alice", "age": 25}
# 6. 集合(Set)
my_set = {1, 2, 3, 3, 3} # 自动去重,结果为 {1, 2, 3}
# 7. 布尔值(Boolean)
flag = True # 或 False
# 8. 空值(None)
nothing = None可变与不可变类型:
python
# 不可变类型:数字、字符串、元组
a = 10
print(id(a)) # 140735892234576
a += 1
print(id(a)) # 140735892234608,id 改变,创建了新对象
s = "hello"
print(id(s)) # 140735892234700
s += " world"
print(id(s)) # 140735892234800,id 改变
# 可变类型:列表、字典、集合
lst = [1, 2, 3]
print(id(lst)) # 140735892234900
lst.append(4)
print(id(lst)) # 140735892234900,id 不变类型转换:
python
# 常用类型转换
int("10") # 10
float("3.14") # 3.14
str(100) # "100"
list("abc") # ['a', 'b', 'c']
tuple([1,2,3]) # (1, 2, 3)
set([1,2,2,3]) # {1, 2, 3}
dict([("a",1), ("b",2)]) # {'a': 1, 'b': 2}
# 判断类型
type(10) # <class 'int'>
isinstance(10, int) # True
isinstance([1,2], (list, tuple)) # True2. 列表、元组、字典、集合的区别
问题:列表、元组、字典、集合有什么区别?使用场景分别是什么?
答案:
| 特性 | 列表 (List) | 元组 (Tuple) | 字典 (Dict) | 集合 (Set) |
|---|---|---|---|---|
| 语法 | [1, 2, 3] | (1, 2, 3) | {"a": 1} | {1, 2, 3} |
| 是否可变 | 是 | 否 | 是 | 是 |
| 是否有序 | 是 | 是 | Python 3.7+ 是 | 否 |
| 是否可重复 | 是 | 是 | 键不可重复 | 否 |
| 访问方式 | 索引 | 索引 | 键 | 无 |
| 查询速度 | O(n) | O(n) | O(1) | O(1) |
使用场景:
python
# 列表:需要有序、可变的集合
# 场景:存储同类型数据,需要频繁增删改
users = ["Alice", "Bob", "Charlie"]
users.append("David") # 添加元素
users.sort() # 排序
# 元组:不可变的有序集合
# 场景:函数返回多个值,作为字典的键,保护数据不被修改
point = (10, 20) # 坐标
person = ("Alice", 25, "Engineer") # 记录
# 字典:键值对映射
# 场景:快速查找,存储对象属性
user_info = {
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
print(user_info["name"]) # O(1) 查找
# 集合:无序不重复元素
# 场景:去重,集合运算(交集、并集、差集)
tags = {"python", "web", "backend"}
tags.add("database")
print("python" in tags) # True,O(1) 查找
# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a & b # 交集: {3, 4}
a | b # 并集: {1, 2, 3, 4, 5, 6}
a - b # 差集: {1, 2}
a ^ b # 对称差集: {1, 2, 5, 6}3. 字符串操作
问题:Python 中常用的字符串操作方法有哪些?
答案:
python
s = " Hello, Python World! "
# 1. 大小写转换
s.upper() # " HELLO, PYTHON WORLD! "
s.lower() # " hello, python world! "
s.title() # " Hello, Python World! "
s.capitalize() # " hello, python world! "
# 2. 去除空白
s.strip() # "Hello, Python World!"
s.lstrip() # "Hello, Python World! "
s.rstrip() # " Hello, Python World!"
# 3. 查找和替换
s.find("Python") # 9,找不到返回 -1
s.index("Python") # 9,找不到抛出异常
s.replace("Python", "Java") # " Hello, Java World! "
s.count("o") # 2,统计出现次数
# 4. 分割和连接
s.split(",") # [' Hello', ' Python World! ']
"-".join(["a", "b", "c"]) # "a-b-c"
# 5. 判断方法
"123".isdigit() # True
"abc".isalpha() # True
"abc123".isalnum() # True
" ".isspace() # True
"Hello".startswith("He") # True
"World!".endswith("!") # True
# 6. 格式化字符串
name = "Alice"
age = 25
# % 格式化
"My name is %s, I'm %d years old." % (name, age)
# str.format()
"My name is {}, I'm {} years old.".format(name, age)
"My name is {0}, I'm {1} years old.".format(name, age)
"My name is {n}, I'm {a} years old.".format(n=name, a=age)
# f-string(推荐,Python 3.6+)
f"My name is {name}, I'm {age} years old."
f"Pi is approximately {3.14159:.2f}" # Pi is approximately 3.14
# 7. 字符串切片
s = "Hello, World!"
s[0:5] # "Hello"
s[7:] # "World!"
s[:5] # "Hello"
s[::2] # "Hlo ol!"(步长为2)
s[::-1] # "!dlroW ,olleH"(反转)4. 列表推导式
问题:什么是列表推导式?如何使用?
答案:
python
# 基本语法:[表达式 for 变量 in 可迭代对象 if 条件]
# 1. 基本用法
# 传统方式
squares = []
for x in range(10):
squares.append(x ** 2)
# 列表推导式
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 2. 带条件过滤
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 3. 多重循环
pairs = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
# 4. 嵌套列表推导式
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 转置
transposed = [[row[i] for row in matrix] for i in range(3)]
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# 5. 字典推导式
square_dict = {x: x**2 for x in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 6. 集合推导式
square_set = {x**2 for x in range(10)}
# {0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
# 7. 生成器表达式(节省内存)
sum_of_squares = sum(x**2 for x in range(1000000))
# 8. 复杂示例
# 处理嵌套数据
users = [
{"name": "Alice", "age": 25, "active": True},
{"name": "Bob", "age": 30, "active": False},
{"name": "Charlie", "age": 35, "active": True}
]
# 获取活跃用户的名字
active_names = [u["name"] for u in users if u["active"]]
# ['Alice', 'Charlie']
# 按年龄分组
age_groups = {
"young": [u["name"] for u in users if u["age"] < 30],
"old": [u["name"] for u in users if u["age"] >= 30]
}
# {'young': ['Alice'], 'old': ['Bob', 'Charlie']}5. 函数定义与参数
问题:Python 函数有哪些参数类型?如何使用?
答案:
python
# 1. 位置参数
def greet(name, greeting):
return f"{greeting}, {name}!"
greet("Alice", "Hello") # "Hello, Alice!"
# 2. 默认参数
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Alice", "Hi") # "Hi, Alice!"
# 注意:默认参数不要使用可变对象
def bad_append(item, items=[]):
items.append(item)
return items
bad_append(1) # [1]
bad_append(2) # [1, 2] - 意外结果!
# 正确做法
def good_append(item, items=None):
if items is None:
items = []
items.append(item)
return items
# 3. 关键字参数
def person_info(name, age, city):
return f"{name}, {age}, lives in {city}"
person_info(age=25, city="Beijing", name="Alice")
# 4. 可变参数 *args
def sum_all(*args):
return sum(args)
sum_all(1, 2, 3, 4) # 10
sum_all() # 0
# args 是元组
def print_args(*args):
print(type(args)) # <class 'tuple'>
for arg in args:
print(arg)
# 5. 关键字可变参数 **kwargs
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="Beijing")
# 6. 参数顺序
def func(pos1, pos2, default="default", *args, **kwargs):
print(f"pos1: {pos1}")
print(f"pos2: {pos2}")
print(f"default: {default}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
func(1, 2, 3, 4, 5, a=6, b=7)
# pos1: 1
# pos2: 2
# default: 3
# args: (4, 5)
# kwargs: {'a': 6, 'b': 7}
# 7. 强制关键字参数(Python 3)
def func(a, b, *, c, d):
"""c 和 d 必须通过关键字传递"""
pass
func(1, 2, c=3, d=4) # 正确
# func(1, 2, 3, 4) # 错误!
# 8. 解包参数
def add(a, b, c):
return a + b + c
nums = [1, 2, 3]
add(*nums) # 6,等价于 add(1, 2, 3)
data = {"a": 1, "b": 2, "c": 3}
add(**data) # 6,等价于 add(a=1, b=2, c=3)6. 面向对象编程
问题:Python 中的类、继承、多态是如何实现的?
答案:
python
# 1. 类的定义
class Person:
# 类属性
species = "Homo sapiens"
# 构造方法
def __init__(self, name, age):
self.name = name # 实例属性
self._age = age # 约定:受保护属性
self.__id = 12345 # 私有属性(名称改写)
# 实例方法
def introduce(self):
return f"I'm {self.name}, {self._age} years old"
# 类方法
@classmethod
def create_anonymous(cls):
return cls("Anonymous", 0)
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 属性装饰器
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
# 特殊方法
def __str__(self):
return f"Person({self.name}, {self._age})"
def __repr__(self):
return f"Person('{self.name}', {self._age})"
def __eq__(self, other):
if not isinstance(other, Person):
return False
return self.name == other.name and self._age == other._age
# 2. 继承
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # 调用父类构造
self.student_id = student_id
self.courses = []
def enroll(self, course):
self.courses.append(course)
# 方法重写
def introduce(self):
base = super().introduce()
return f"{base}, Student ID: {self.student_id}"
# 3. 多继承
class Flyable:
def fly(self):
return "I can fly!"
class Swimmable:
def swim(self):
return "I can swim!"
class Duck(Flyable, Swimmable):
pass
duck = Duck()
duck.fly() # "I can fly!"
duck.swim() # "I can swim!"
# MRO(方法解析顺序)
print(Duck.__mro__)
# (<class 'Duck'>, <class 'Flyable'>, <class 'Swimmable'>, <class 'object'>)
# 4. 抽象基类
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
@abstractmethod
def move(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
def move(self):
return "Running on 4 legs"
# animal = Animal() # 错误!不能实例化抽象类
dog = Dog() # 正确
# 5. 混入(Mixin)
class JSONSerializableMixin:
def to_json(self):
import json
return json.dumps(self.__dict__)
class LoggableMixin:
def log(self, message):
print(f"[{self.__class__.__name__}] {message}")
class User(JSONSerializableMixin, LoggableMixin):
def __init__(self, name):
self.name = name
user = User("Alice")
print(user.to_json()) # {"name": "Alice"}
user.log("Created") # [User] Created7. 异常处理
问题:Python 中如何处理异常?有哪些最佳实践?
答案:
python
# 1. 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# 2. 捕获多种异常
try:
# 可能抛出多种异常的代码
value = int("not a number")
except (ValueError, TypeError) as e:
print(f"Error: {e}")
# 3. 分别处理不同异常
try:
risky_operation()
except ValueError as e:
print(f"Value error: {e}")
except FileNotFoundError as e:
print(f"File not found: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# 4. else 和 finally
try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found")
else:
# 没有异常时执行
print(f"Read {len(data)} characters")
finally:
# 无论是否异常都执行
file.close()
print("File closed")
# 5. 自定义异常
class ValidationError(Exception):
"""数据验证错误"""
pass
class BusinessError(Exception):
"""业务逻辑错误"""
def __init__(self, message, code):
super().__init__(message)
self.code = code
def validate_age(age):
if age < 0:
raise ValidationError("Age cannot be negative")
if age > 150:
raise ValidationError("Age is unrealistic")
return age
# 6. 异常链
def process_data(data):
try:
result = parse_data(data)
except ValueError as e:
raise ProcessingError("Failed to process data") from e
# 7. 上下文管理器(推荐用于资源管理)
# 传统方式
file = open("file.txt", "r")
try:
data = file.read()
finally:
file.close()
# 使用 with 语句
with open("file.txt", "r") as file:
data = file.read()
# 文件自动关闭
# 自定义上下文管理器
from contextlib import contextmanager
@contextmanager
def managed_resource(name):
print(f"Acquiring {name}")
resource = {"name": name}
try:
yield resource
finally:
print(f"Releasing {name}")
with managed_resource("database") as db:
print(f"Using {db['name']}")
# 输出:
# Acquiring database
# Using database
# Releasing database
# 8. 异常处理最佳实践
# 不要捕获所有异常而不处理
try:
do_something()
except: # 不推荐!捕获所有异常包括 KeyboardInterrupt
pass
# 推荐:捕获具体异常
try:
do_something()
except SpecificError as e:
handle_error(e)
# 不要忽略异常
try:
risky_operation()
except SomeError:
pass # 不推荐!
# 推荐:至少记录日志
import logging
try:
risky_operation()
except SomeError as e:
logging.error(f"Operation failed: {e}")
raise # 重新抛出或处理8. 文件操作
问题:Python 中如何进行文件读写操作?
答案:
python
# 1. 基本文件读写
# 读取整个文件
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read()
# 逐行读取
with open("file.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
# 读取为列表
with open("file.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
# 写入文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# 追加模式
with open("log.txt", "a", encoding="utf-8") as f:
f.write("New log entry\n")
# 2. 文件模式
# "r" - 读取(默认)
# "w" - 写入(覆盖)
# "a" - 追加
# "x" - 创建(文件存在则失败)
# "b" - 二进制模式
# "+" - 读写模式
# 二进制文件
with open("image.png", "rb") as f:
data = f.read()
# 3. 使用 pathlib(推荐)
from pathlib import Path
# 创建路径
p = Path("/home/user/documents")
file_path = p / "file.txt" # 使用 / 连接路径
# 检查存在性
if file_path.exists():
print("File exists")
# 读取
content = file_path.read_text(encoding="utf-8")
# 写入
file_path.write_text("Hello, World!", encoding="utf-8")
# 遍历目录
for file in p.glob("*.txt"):
print(file)
# 递归遍历
for file in p.rglob("*.py"):
print(file)
# 创建目录
new_dir = Path("new_directory")
new_dir.mkdir(parents=True, exist_ok=True)
# 4. CSV 文件
import csv
# 读取 CSV
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# 写入 CSV
with open("output.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 25, "Beijing"])
writer.writerow(["Bob", 30, "Shanghai"])
# 使用 DictReader/DictWriter
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["Name"], row["Age"])
# 5. JSON 文件
import json
data = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "coding"]
}
# 写入 JSON
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 读取 JSON
with open("data.json", "r", encoding="utf-8") as f:
loaded_data = json.load(f)
# 6. 大文件处理
def process_large_file(filename):
"""逐块处理大文件"""
chunk_size = 1024 * 1024 # 1MB
with open(filename, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
process_chunk(chunk)
# 使用生成器处理大文件
def read_large_file(filename):
"""惰性读取大文件"""
with open(filename, "r", encoding="utf-8") as f:
for line in f:
yield line.strip()
# 使用
for line in read_large_file("huge_file.txt"):
process_line(line)9. 常用内置函数
问题:Python 中有哪些常用的内置函数?
答案:
python
# 1. 类型转换
int("10") # 10
float("3.14") # 3.14
str(100) # "100"
bool(1) # True
list("abc") # ['a', 'b', 'c']
dict([("a", 1)]) # {'a': 1}
# 2. 数学运算
abs(-5) # 5
round(3.14159, 2) # 3.14
divmod(17, 5) # (3, 2) - 商和余数
pow(2, 3) # 8
sum([1, 2, 3]) # 6
min([1, 2, 3]) # 1
max([1, 2, 3]) # 3
# 3. 序列操作
len([1, 2, 3]) # 3
range(5) # range(0, 5)
range(1, 10, 2) # range(1, 10, 2) - 1, 3, 5, 7, 9
enumerate(["a", "b"]) # [(0, 'a'), (1, 'b')]
zip([1, 2], ["a", "b"]) # [(1, 'a'), (2, 'b')]
map(str, [1, 2, 3]) # ['1', '2', '3']
filter(lambda x: x > 0, [-1, 1, 2]) # [1, 2]
sorted([3, 1, 2]) # [1, 2, 3]
reversed([1, 2, 3]) # [3, 2, 1]
# 4. 输入输出
print("Hello", "World", sep="-") # Hello-World
input("Enter your name: ")
open("file.txt", "r")
# 5. 对象操作
type(10) # <class 'int'>
isinstance(10, int) # True
hasattr(obj, "name") # 检查属性
getattr(obj, "name") # 获取属性
setattr(obj, "name", value) # 设置属性
dir(obj) # 列出所有属性和方法
id(obj) # 对象唯一标识
hash(obj) # 哈希值
# 6. 逻辑判断
all([True, True, False]) # False
any([False, True, False]) # True
callable(func) # 是否可调用
# 7. 函数式编程
from functools import reduce
# lambda
square = lambda x: x ** 2
# map
list(map(lambda x: x * 2, [1, 2, 3])) # [2, 4, 6]
# filter
list(filter(lambda x: x > 0, [-1, 1, 2])) # [1, 2]
# reduce
reduce(lambda x, y: x + y, [1, 2, 3, 4]) # 10
# 8. 高级函数
# zip unpacking
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
nums, letters = zip(*pairs)
# nums = (1, 2, 3)
# letters = ('a', 'b', 'c')
# enumerate 从指定索引开始
list(enumerate(['a', 'b', 'c'], start=1)) # [(1, 'a'), (2, 'b'), (3, 'c')]
# sorted 自定义排序
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
sorted(students, key=lambda s: s["score"], reverse=True)10. Python 高级特性
问题:Python 有哪些高级特性?如何使用?
答案:
python
# 1. 解包操作
# 元组解包
a, b = 1, 2
# 扩展解包(Python 3)
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]
*beginning, last = [1, 2, 3, 4, 5]
# beginning = [1, 2, 3, 4], last = 5
first, *middle, last = [1, 2, 3, 4, 5]
# first = 1, middle = [2, 3, 4], last = 5
# 字典解包
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 2. 海象运算符 := (Python 3.8+)
# 传统方式
n = len(data)
if n > 10:
print(f"Length is {n}")
# 使用海象运算符
if (n := len(data)) > 10:
print(f"Length is {n}")
# 在 while 循环中使用
while (line := input()) != "quit":
print(f"You entered: {line}")
# 3. 类型注解(Python 3.5+)
from typing import List, Dict, Optional, Union, Callable
def greet(name: str) -> str:
return f"Hello, {name}"
def process_data(data: List[int]) -> Dict[str, int]:
return {"count": len(data), "sum": sum(data)}
def find_user(user_id: int) -> Optional[Dict]:
# 可能返回 None 或字典
pass
def parse_value(value: Union[str, int]) -> str:
# 参数可以是 str 或 int
return str(value)
def apply_operation(func: Callable[[int], int], value: int) -> int:
return func(value)
# 4. 数据类(Python 3.7+)
from dataclasses import dataclass, field
from typing import List
@dataclass
class Person:
name: str
age: int = 0
friends: List[str] = field(default_factory=list)
def __post_init__(self):
if self.age < 0:
raise ValueError("Age cannot be negative")
person = Person("Alice", 25)
print(person) # Person(name='Alice', age=25, friends=[])
# 5. 枚举类
from enum import Enum, auto
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
class Status(Enum):
PENDING = auto()
RUNNING = auto()
COMPLETED = auto()
print(Color.RED) # Color.RED
print(Color.RED.name) # RED
print(Color.RED.value) # 1
# 6. 命名元组
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 10 20
# typing.NamedTuple(支持类型注解)
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
# 7. 默认字典和计数器
from collections import defaultdict, Counter
# 默认字典
dd = defaultdict(list)
dd['key'].append(1)
dd['key'].append(2)
# dd['key'] = [1, 2]
# 计数器
counter = Counter(['a', 'b', 'a', 'c', 'a', 'b'])
print(counter) # Counter({'a': 3, 'b': 2, 'c': 1})
print(counter.most_common(2)) # [('a', 3), ('b', 2)]
# 8. 链式映射
from collections import ChainMap
defaults = {"theme": "light", "language": "en"}
user_prefs = {"theme": "dark"}
combined = ChainMap(user_prefs, defaults)
print(combined["theme"]) # dark(来自 user_prefs)
print(combined["language"]) # en(来自 defaults)