
Python以其简洁优雅的语法和强大的功能深受开发者喜爱。本文将介绍15个高效的Python代码写法,不仅能提升代码的可读性和性能,还能让开发效率提升。本文所有示例均兼容Python 3.8+版本。
# 传统写法
squares = {}
foriinrange(5):
squares[i] = i*i
# 高效写法
squares = {i: i*iforiinrange(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}name, age = "Alice", 25
# 过时写法
print("My name is {} and I'm {} years old".format(name, age))
# 推荐写法(f-string)
print(f"My name is {name} and I'm {age} years old")# 一行赋值
a, b, c = 1, 2, 3
# 优雅交换
a, b = b, afruits = ['apple', 'banana', 'cherry']
# 不推荐
foriinrange(len(fruits)):
print(i, fruits[i])
# 推荐
foridx, fruitinenumerate(fruits, start=1): # 索引从 1 开始
print(idx, fruit)names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
# 不推荐
foriinrange(len(names)):
print(names[i], ages[i])
# 推荐
forname, ageinzip(names, ages):
print(name, age)fromcollectionsimportdefaultdict
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
# 传统写法
counter = {}
forwinwords:
counter[w] = counter.get(w, 0) +1
# 高效写法
counter = defaultdict(int)
forwinwords:
counter[w] += 1numbers = [1, 2, 3, 4, 5]
has_even = any(n%2 == 0forninnumbers) # True
all_positive = all(n>0forninnumbers) # Truedeflog(*args, **kwargs):
print("Positional:", args)
print("Keywords :", kwargs)
log(1, 2, 3, name="Alice", age=25)# 传统写法
data = {}
if'count'notindata:
data['count'] = 0
data['count'] += 1
# 推荐写法
data = {}
data.setdefault('count', 0)
data['count'] += 1__init__ 已成为历史fromdataclassesimportdataclass
@dataclass(slots=True) # slots=True 节省内存(3.10+)
classPerson:
name: str
age: int
email: str|None = None # 3.10+ 联合类型写法
p = Person("Alice", 25)
print(p) # Person(name='Alice', age=25, email=None):=:在表达式里完成赋值,减少重复 I/O3.8+ 新特性,减少重复计算。
# 从日志里实时提取 ERROR 行并计数
importsys, re
total = 0
whilechunk := sys.stdin.read(8192):
errors = re.findall(r'ERROR', chunk)
total += len(errors)
print('ERROR 出现次数:', total)# 快速统计 10 G 大文件行数
frompathlibimportPath
file = Path('big.log')
line_cnt = sum(1for_infile.open(encoding='utf-8', errors='ignore'))
print('总行数:', line_cnt)functools.lru_cache 自动缓存fromfunctoolsimportlru_cache
@lru_cache(maxsize=None) # 无界缓存
deffib(n: int) ->int:
returnnifn<2elsefib(n-1) +fib(n-2)
print(fib(100)) # 瞬间返回
print(fib.cache_info()) # 查看命中情况# 一行解析命令行指令
defparse(cmd: str):
matchcmd.split():
case ['quit'|'exit']:
return'SHUTDOWN'
case ['add', x, y] ifx.isdigit() andy.isdigit():
returnint(x) +int(y)
case_:
return'UNKNOWN'
print(parse('add 3 5')) # 8
print(parse('quit')) # SHUTDOWN# 一键并发下载 100 张图片
importasyncio, aiohttp, time
frompathlibimportPath
asyncdeffetch(url: str, session: aiohttp.ClientSession, dst: Path):
asyncwithsession.get(url) asresp:
dst.write_bytes(awaitresp.read())
asyncdefbulk_download(urls: list[str], folder='imgs'):
Path(folder).mkdir(exist_ok=True)
asyncwithaiohttp.ClientSession() assession:
tasks = [
fetch(u, session, Path(folder) /f'{i:03}.jpg')
fori, uinenumerate(urls)
]
awaitasyncio.gather(*tasks)
if__name__ == '__main__':
urls = [f'https://picsum.photos/200/300?random={i}'foriinrange(100)]
start = time.perf_counter()
asyncio.run(bulk_download(urls))
print('全部下载完成,耗时:', time.perf_counter() -start, 's')fromcollectionsimportdefaultdict
fromdataclassesimportdataclass
@dataclass
classProduct:
name: str
price: float
category: str
products = [
Product("Laptop", 999.99, "Electronics"),
Product("Phone", 699.99, "Electronics"),
Product("Book", 19.99, "Books"),
Product("Chair", 149.99, "Furniture"),
Product("Table", 199.99, "Furniture"),
]
# 按类别聚合价格
group = defaultdict(list)
forpinproducts:
group[p.category].append(p.price)
# 字典推导式计算平均价
avg_price = {c: sum(prices) /len(prices) forc, pricesingroup.items()}
print(avg_price)
# {'Electronics': 849.99, 'Books': 19.99, 'Furniture': 174.99}本文介绍了15个Python高效代码写法,在实际开发中逐步应用这些技巧,并根据具体场景选择最适合的方法。这些技巧可以帮助:
1、编写更简洁的代码
2、提高代码执行效率
3、增强代码可读性
4、减少重复代码
5、提升开发效率
“无他,惟手熟尔”!有需要就用起来。
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!