下面的技巧可以帮助你在Python编程时提高代码质量,优化性能,或者只是让你的代码看起来更酷。
1. 交换两个变量的值
Python允许你以简洁的语法交换两个变量的值,不需要借助临时变量。
a, b = 5, 10
a, b = b, a # 交换 a 和 b
print(a, b) # 输出: 10 5
2. 链式比较
Python支持链式比较,可以在一个表达式中进行多个条件判断。
x = 10
if 1 < x < 20:
print("x 在 1 到 20 之间")
上面的代码相当于 if 1 < x and x < 20:
,但是更加简洁和可读。
3. 字典的默认值
你可以使用 defaultdict
来自动为字典中的键设置默认值,从而避免使用 if
判断键是否存在。
from collections import defaultdict
d = defaultdict(int) # 默认值为 int 类型(即 0)
d["apple"] += 1
print(d["apple"]) # 输出: 1
print(d["banana"]) # 输出: 0, 如果没有 "banana",会自动返回默认值 0
4. 列表推导式
Python的列表推导式(List Comprehension)是一种非常简洁的创建列表的方式,它使得代码更加简洁和高效。
# 创建一个包含1到10的平方数的列表
squares = [x ** 2 for x in range(1, 11)]
print(squares) # 输出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
5. 使用else
与for
一起进行循环结束后的操作
你可以在for
循环的结束后使用else
语句,它只会在循环没有被break
语句打断时执行。
for i in range(5):
if i == 3:
print("Found 3!")
break
else:
print("Did not find 3.") # 如果没有 break,才会执行这句
6. 多行字符串(三引号字符串)
使用三引号('''
或 """
)可以创建多行字符串,不需要担心换行符。
text = """This is a multi-line string.
It can span across multiple lines
without using escape characters."""
print(text)
7. Python中的一行 if
条件表达式(Ternary Operator)
你可以在一行中使用三元操作符来进行条件判断。
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result) # 输出: Even
8. 使用 *args
和 **kwargs
处理不定参数
*args
用于处理位置参数的可变数量,而 **kwargs
用于处理关键字参数的可变数量。
def fun(*args, **kwargs):
print(args) # 输出位置参数
print(kwargs) # 输出关键字参数
fun(1, 2, 3, name="Alice", age=30)
输出:
(1, 2, 3)
{'name': 'Alice', 'age': 30}
9. enumerate()
函数
enumerate()
函数可以让你在遍历列表时同时获取元素的索引。
fruits = ["apple", "banana", "cherry"]
for idx, fruit in enumerate(fruits):
print(idx, fruit)
输出:
0 apple
1 banana
2 cherry
10. 函数内嵌函数(闭包)
在Python中,函数可以定义在其他函数内,形成一个闭包,这对于很多需要封装的场景非常有用。
def outer_func(x):
def inner_func(y):
return x + y
return inner_func
add_10 = outer_func(10)
print(add_10(5)) # 输出: 15
11. 使用 zip()
函数将两个列表合并
zip()
函数可以将两个或更多的列表合并成元组列表。
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 88]
combined = list(zip(names, scores))
print(combined) # 输出: [('Alice', 85), ('Bob', 90), ('Charlie', 88)]
12. 单行函数(lambda表达式)
lambda
表达式允许你定义简单的匿名函数,适用于函数作为参数的场景。
# 定义一个简单的匿名函数
add = lambda x, y: x + y
print(add(3, 4)) # 输出: 7
13. 使用 join()
方法合并字符串
join()
是一个高效地将多个字符串合并成一个字符串的方法。
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # 输出: Python is awesome
14. 使用 sorted()
排序并保持原列表不变
sorted()
返回一个新的排序后的列表,而不会改变原来的列表。
numbers = [5, 3, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 3, 5, 9]
print(numbers) # 输出: [5, 3, 9, 1] 原列表不变
15. 使用 collections.Counter
计算出现频率
collections.Counter
是一个非常有用的类,能够帮助你快速统计列表中元素的出现频率。
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "banana"]
word_count = Counter(words)
print(word_count) # 输出: Counter({'banana': 3, 'apple': 2, 'cherry': 1})
16. 可变默认参数问题
Python中默认参数值是共享的(引用传递)。如果默认参数是可变对象(如列表或字典),它们会被所有函数调用共享。这是一个常见的“陷阱”。
def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list
print(append_to_list(1)) # 输出: [1]
print(append_to_list(2)) # 输出: [1, 2](默认列表被共享了)
解决这个问题的办法是将可变默认参数设置为 None
,然后在函数内部初始化:
def append_to_list(value, my_list=None):
if my_list is None:
my_list = []
my_list.append(value)
return my_list
print(append_to_list(1)) # 输出: [1]
print(append_to_list(2)) # 输出: [2]
17. 使用any()
和all()
进行条件检查
any()
和all()
是两个非常有用的内置函数,它们分别检查一个可迭代对象中的任意或所有条件是否为True
。
# any() 检查是否有任何元素为True
values = [0, "", None, 3]
if any(values):
print("有元素为True")
else:
print("没有元素为True") # 输出: 有元素为True
# all() 检查是否所有元素都为True
if all([1, 2, 3]):
print("所有元素都为True")
else:
print("有元素为False") # 输出: 所有元素都为True
18. 反转列表
反转一个列表非常简单,只需使用[::-1]
切片操作:
my_list = [1, 2, 3, 4]
reversed_list = my_list[::-1]
print(reversed_list) # 输出: [4, 3, 2, 1]
19. 利用itertools
模块实现无限循环
itertools.cycle()
可以用于无限循环一个可迭代对象。如果你想要一直循环遍历一个列表,cycle()
非常有用。
import itertools
colors = ['red', 'green', 'blue']
for color in itertools.cycle(colors):
print(color)
# 将循环一定次数以避免无限输出
if color == 'blue':
break # 输出: red green blue red green blue...
20. 利用collections.deque
实现高效队列
deque
是一个双端队列,它支持在两端快速插入和删除操作。它比使用普通的列表要高效,特别是在队列的两端进行操作时。
from collections import deque
q = deque([1, 2, 3, 4])
q.append(5) # 从右端添加元素
q.appendleft(0) # 从左端添加元素
q.pop() # 删除并返回右端元素
q.popleft() # 删除并返回左端元素
print(q) # 输出: deque([1, 2, 3])
21. 函数装饰器
函数装饰器允许你在不修改函数代码的情况下增加额外的功能。例如,以下是一个简单的日志装饰器:
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice") # 输出:
# Calling function say_hello
# Hello, Alice!
22. 使用__getitem__
实现自定义索引
通过实现__getitem__
方法,你可以让一个类的实例支持索引访问(如列表那样)。
class MyList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
print(f"Getting item at index {index}")
return self.items[index]
my_list = MyList([10, 20, 30])
print(my_list[1]) # 输出: Getting item at index 1 \n 20
23. 集合去重
利用集合的特性,可以非常快速地去除列表中的重复项。集合自动删除重复的元素。
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))
print(unique_list) # 输出: [1, 2, 3, 4, 5]
24. 通过join()
拼接字符串
当你需要拼接多个字符串时,join()
方法比使用+
运算符更加高效,尤其是当字符串较多时。
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # 输出: Python is awesome
25. Python中的with
语句
with
语句用于处理文件或其他需要清理的资源,能够自动管理资源的获取和释放,避免出现忘记关闭文件等资源泄露的问题。
with open('file.txt', 'r') as file:
content = file.read()
print(content)
# 无需手动调用 file.close(),with语句会自动关闭文件
26. setdefault()
避免KeyError
setdefault()
是字典的一个方法,可以用来获取某个键的值,如果该键不存在,则会自动设置默认值。
my_dict = {"apple": 3, "banana": 5}
# 如果 "orange" 不存在,设置为默认值 0
print(my_dict.setdefault("orange", 0)) # 输出: 0
print(my_dict) # 输出: {'apple': 3, 'banana': 5, 'orange': 0}
27. f-string
格式化字符串
从Python 3.6开始,f-string提供了一种快速且可读性更强的方式来格式化字符串。
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.") # 输出: My name is Alice and I am 25 years old.
28. 使用__call__()
使对象可调用
你可以通过定义__call__
方法,使得你的对象像函数一样被调用。
class Adder:
def __init__(self, value):
self.value = value
def __call__(self, x):
return self.value + x
add_five = Adder(5)
print(add_five(10)) # 输出: 15
29. 通过namedtuple
命名元组
namedtuple
是collections
模块中的一个类,它可以给元组的元素起个名字,这样可以提高代码的可读性。
from collections import namedtuple
# 创建一个表示点的命名元组
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y) # 输出: 1 2
30. 多重继承与super()
Python支持多重继承,并且可以使用super()
来调用父类的方法,尤其是当多继承时,它可以帮助你避免调用顺序问题。
class A:
def hello(self):
print("Hello from A")
class B(A):
def hello(self):
super().hello()
print("Hello from B")
class C(A):
def hello(self):
super().hello()
print("Hello from C")
class D(B, C):
def hello(self):
super().hello()
print("Hello from D")
d = D()
d.hello()
输出:
Hello from A
Hello from C
Hello from B
Hello from D
31. 使用yield
生成器实现懒加载
yield
可以让你在函数内部生成一个迭代器,允许你懒加载数据(即按需生成数据),在处理大量数据时非常高效。
def generate_numbers(n):
for i in range(n):
yield i
gen = generate_numbers(5)
for number in gen:
print(number) # 输出: 0 1 2 3 4
32. filter()
函数
filter()
函数允许你从可迭代对象中筛选出满足特定条件的元素,返回一个新的迭代器。
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出: [2, 4, 6]
我什么也没忘,但是有些事只适合收藏。不能说,也不能想,却又不能忘