优雅书写Python代码的11个技巧
关于Python的几个编程小技巧,希望能希望能提高大家的编程效率
enumerate 替代 range(len(x))
data = [1, 2, 3, 5]
# BAD:
for i in range(len(data)):
if data[i] < 3:
data[i] = 0
print(data)
# GOOD:
for idx, num in enumerate(data):
if num < 3:
data[idx] = 0
print(data)
########## output ##########
[0, 0, 3, 5]
[0, 0, 3, 5]
列表表达式替代循环语句
# BAD:
squares = []
for i in range(10):
squares.append(i*i)
print(squares)
# GOOD:
squares = [i*i for i in range(10)]
print(squares)
########## output ##########
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
使用 sorted() 对复杂对象排序
# data = [1, 3, 4, 5, -1]
data = (1, 3, 4, 5, -1)
sorted_data = sorted(data, reverse=True)
print(sorted_data)
data = [{'name':'Jack', 'age':6},
{'name':'Rose', 'age':5},
{'name':'Jia', 'age':16}]
sorted_data = sorted(data, key=lambda x: x['age'] )
print(sorted_data)
########## output ##########
[5, 4, 3, 1, -1]
[{'name': 'Rose', 'age': 5}, {'name': 'Jack', 'age': 6}, {'name': 'Jia', 'age': 16}]
使用 sets() 保存唯一值
my_list = [1,3,4,5,6,6,7,7,7,7]
my_set = set(my_list)
print(my_set)
print({3,4,5,6,6,8,2,4,5,5})
########## output ##########
{1, 3, 4, 5, 6, 7}
{2, 3, 4, 5, 6, 8}
使用迭代器节省内存
import sys
my_list = [i for i in range(1000)]
print(sum(my_list))
print(sys.getsizeof(my_list), 'bytes')
my_gen = (i for i in range(1000))
print(sum(my_gen))
print(sys.getsizeof(my_gen), 'bytes')
########## output ##########
499500
9016 bytes
499500
112 bytes
使用 .get() 和 .setdefault() 设置字典返回默认值
my_dict = {'item':'football', 'price':100}
count = my_dict.get('count', 0)
print(count)
count = my_dict.setdefault('count', 0)
print(count)
print(my_dict)
########## output ##########
0
0
{'item': 'football', 'price': 100, 'count': 0}##
使用 collection.Counter 统计字典元素数量
from collections import Counter
my_list = [1,2,3,5,6,6,3,5,6,6,6]
counter = Counter(my_list)
print(counter)
print(counter[2])
print(counter.most_common(2))
########## output ##########
Counter({6: 5, 3: 2, 5: 2, 1: 1, 2: 1})
1
[(6, 5), (3, 2)]
使用 f-string 输出字符串**(python3.6+)**
name = 'Alex'
print(f'hello {name}')
i = 10
print(f'{i} squared is {i*i}')
########## output ##########
hello Alex
10 squared is 100
使用 .join()连接分割字符串
list_of_string = ['Hello','my','world','!']
# BAD:
my_string = ''
for i in list_of_string:
my_string += i + ' '
print(my_string)
# GOOD:
my_string = ' '.join(list_of_string)
print(my_string)
########## output ##########
Hello my world !
Hello my world !
使用 {**d1,**d2} 合并字典元素(Python3.5+)
d1 = {'item':'football', 'price':100}
d2 = {'item':'football', 'count':10}
merge_dict = {**d1, **d2}
print(merge_dict)
########## output ##########
{'item': 'football', 'price': 100, 'count': 10}
使用 if x in [abc] 简化元素查询
colors = ['blue', 'green', 'red']
c = 'red'
if c in colors:
print(f'{c} is main color.')
########## output ##########
red is main color.
- 点击一下,查看源视频 😉😉