Python 编码技巧


Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。要写出 Pythonic(优雅的、地道的、整洁的)代码,需要多看多学大牛们写的代码。

1、交互赋值
a = 1
b = 2
temp = a
a = b
b = temp

# 推荐
a, b = b, a
2 、拆分列表
my_list = ['A', 'B', 'C']
simple0 = simple_list[0]
simple1 = simple_list[1]
simple2 = simple_list[2]

# 推荐
simpleA, simpleB, simpleC = my_list
3、使用 in 判断语句
if result == 'ok' or result == 1:
    '''代码处理'''

# 推荐 
if result in ['ok', 1]:
    '''代码处理'''
4、使用 join 合并字符串
colors = ['red', 'yellow', 'blue', 'green']
result = ''
for i in colors:
    result += i

# 推荐
colors = ['red', 'yellow', 'blue', 'green']
result = ''.join(colors)
# 避免了多次赋值后丢弃以前的字符串对象
5、遍历列表及索引
my_itmes = ['a', 'b', 'c', 'd', 'e']
i = 0
for item in my_itmes:
    print(i, item)
    i += 1
    
# 推荐
my_itmes = ['a', 'b', 'c', 'd', 'e']
for i, item in enumerate(my_itmes):
    print(i, item)
6、推导式
# 列表推导式
old_list = ['A', 'B', 'C', 'D', 'E']
new_list = [item for item in old_list]

# 字典推导式
dict = {'key1': 'value1', 'key2': 'value2'}
d = {k: v for k, v in dict.items()}

# 集合推导式
simple_set = {x ** 2 for x in [1, -1, 2]}
7、循环嵌套
x_list = ['a', 'b', 'c', 'd']
y_list = ['A', 'B', 'C', 'D']
z_list = ['1', '2', '3', '4']

for x in x_list:
    for y in y_list:
        for z in z_list:
            print(x, y, z)
            
# 推荐
from itertools import product

for x, y, z in product(x_list, y_list, z_list):
    print(x, y, z)
8、生成器替代列表
def calculate(n):
    return n ** 2


def my_range(n):
    i = 0
    result = []
    while i < n:
        result.append(calculate(i))
        i += 1
    return result

# 推荐
def my_range(n):
    i = 0
    while i < n:
        yield calculate(i)
        i += 1
# 生成器适合一边遍历一边计算
9、使用any/all函数
found = False
for item in my_list:
    if condition(item):
        found = True
        break
if found:
    '''代码操作'''

##推荐
if any(condition(item) for item in my_list):
	 '''代码操作'''
    
# any是任意,而all是全部
10、属性
class Clock(object):
    def __init__(self):
        self.__hour = 1

    def __setHour(self, hour):
        self.__hour = hour

    def __getHour(self):
        return self.__hour

    hour = property(__getHour, __setHour)
11、使用 with 处理文件打开
f = open('text.txt')
content = f.read()
f.close()

# 推荐
with open('text.txt') as f:
    content = f.read()
12、使用 with 加锁
import threading

lock = threading.Lock()
lock.acquire()
try:
    '''互斥操作'''
finally:
    lock.release()

# 推荐
import threading
lock = threading.Lock()

with lock:
    '''互斥操作'''
13、使用Counter统计次数
my_list = ['a', 'a', 'b', 'c', 'c', 'c']

def compute(my_list):
    # 词频字典
    my_dict = {}

    for key in my_list:
        if key not in my_dict:
            # 单词不在单词词频字典中, 词频设置为1
            my_dict[key] = 1
        else:
            # 单词在单词词频字典中, 词频加1
            my_dict[key] = my_dict[key] + 1
    return my_dict

# 推荐
from collections import Counter

def compute(my_list):
    # 词频字典
    counter = Counter(my_list)
    return dict(counter)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值