作为一个在 Python 坑里摸爬滚打几年的程序员,我见过太多让人眼前一亮的代码片段。今天整理一些真正实用且优雅的技巧,不是那种炫技的奇淫巧技,而是能让你在实际工作中说出"卧槽,还能这样写?"的实用招数。
让同事怀疑人生的一行代码
1. 字典合并的三种境界
# 菜鸟写法
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
result = {}
for k, v in dict1.items():
result[k] = v
for k, v in dict2.items():
result[k] = v
# 老鸟写法
result = {**dict1, **dict2}
# 大神写法(Python 3.9+)
result = dict1 | dict2
第一次看到
|
操作符合并字典的时候,我怀疑自己学的是假 Python。
2. 列表去重还保持顺序?
# 普通人的写法
def remove_duplicates(lst):
result = []
for item in lst:
if item not in result:
result.append(item)
return result
# 高手的写法
def remove_duplicates(lst):
return list(dict.fromkeys(lst))
利用字典 key 的唯一性,既去重又保持顺序,简直是天才的想法。
3. 交换变量值,这才叫 Pythonic
# C++ 程序员的惯性思维 temp = a a = b b = temp # Python 的优雅 a, b = b, a
这个估计大家都知道,但每次写的时候还是会心一笑。
那些让你怀疑自己智商的技巧
4. 用 zip 处理多个列表
names = ['张三', '李四', '王五']
ages = [25, 30, 35]
cities = ['北京', '上海', '深圳']
# 新手的写法
for i in range(len(names)):
print(f"{names[i]}, {ages[i]}, {cities[i]}")
# 老手的写法
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age}, {city}")
# 更骚的操作:转置矩阵
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
# 结果:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
第一次看到
zip(*matrix)
的时候,感觉打开了新世界的大门。
5. enumerate 的正确打开方式
# 不优雅的写法
items = ['apple', 'banana', 'orange']
for i in range(len(items)):
print(f"{i}: {items[i]}")
# Pythonic 写法
for i, item in enumerate(items):
print(f"{i}: {item}")
# 更高级的用法:指定起始索引
for i, item in enumerate(items, start=1):
print(f"{i}: {item}")
6. collections.Counter 的神奇魔法
from collections import Counter
# 统计字符出现次数
text = "hello world"
counter = Counter(text)
print(counter) # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# 找出最常见的元素
print(counter.most_common(2)) # [('l', 3), ('o', 2)]
# 两个计数器的运算
counter1 = Counter(['a', 'b', 'c', 'a'])
counter2 = Counter(['a', 'b', 'b'])
print(counter1 + counter2) # Counter({'a': 3, 'b': 3, 'c': 1})
325

被折叠的 条评论
为什么被折叠?



