fruits =['apple','banana','orange']# 传统方式for i inrange(len(fruits)):print(f"{i}: {fruits[i]}")# Pythonic方式for i, fruit inenumerate(fruits):print(f"{i}: {fruit}")# 可以指定起始索引for i, fruit inenumerate(fruits, start=1):print(f"{i}: {fruit}")
7. 使用any和all简化条件判断
any和all函数可以简化复杂的条件判断。
numbers =[1,2,3,4,5]# any: 只要有任何一个元素满足条件就返回Trueprint(any(num >4for num in numbers))# True# all: 所有元素都满足条件才返回Trueprint(all(num >0for num in numbers))# Trueprint(all(num >1for num in numbers))# False
8. 使用collections模块中的defaultdict
defaultdict比普通字典更方便处理键不存在的情况。
from collections import defaultdict
# 普通字典会触发KeyError# d = {}# d['key'] += 1# defaultdict会自动初始化
d = defaultdict(int)
d['key']+=1print(d['key'])# 1# 其他常见用法
word_counts = defaultdict(int)
words =['apple','banana','apple','apple','banana']for word in words:
word_counts[word]+=1print(word_counts)# defaultdict(<class 'int'>, {'apple': 3, 'banana': 2})
9. 使用f-strings格式化字符串(Python 3.6+)
f-string是Python 3.6引入的字符串格式化方法,更简洁易读。
name ="Alice"
age =25# 旧方法print("Hi, my name is %s and I'm %d years old."%(name, age))print("Hi, my name is {} and I'm {} years old.".format(name, age))# f-string方法print(f"Hi, my name is {name} and I'm {age} years old.")# 表达式也可用print(f"Next year I'll be {age +1} years old.")# 格式化数字
price =19.99print(f"The price is ${price:.2f}")# The price is $19.99