writing idiomatic python 读书笔记(4)

这篇是三个 字典、集合、元组


字典

(1)使用dict代替switch...case
python中没有switch啊。。。用dict好处多多,面向对象嘛,函数也只是变量一样,使用可以一样来用。
   
   
def apply_operation(left_operand, right_operand, operator):
if operator == '+':
return left_operand + right_operand
elif operator == '-':
return left_operand - right_operand
elif operator == '*':
return left_operand * right_operand
elif operator == '/':
return left_operand / right_operand
要是写出这样的函数,会被说的,代码冗余度高,性能没有
   
   
def apply_operation(left_operand, right_operand, operator):
import operator as op
operator_mapper = {'+': op.add, '-': op.sub,
'*': op.mul, '/': op.truediv}
return operator_mapper[operator](left_operand, right_operand)
函数也只是当做一个value值来用
(2)dict 也是可以用来提供默认参数的。
python中有很多地方可以提供默认参数,dict容易被忘了,使代码清晰可读,必不可少啊
不知道的人:
   
   
log_severity = None
if 'severity' in configuration:
log_severity = configuration['severity']
else:
log_severity = 'Info'
习惯了就提高代码质量:
   
   
log_severity = configuration.get('severity', 'Info')
(3)字典推导
list推导很多人都使用,字典推导却很少人使用。
理解推导语法后可以用来创建一个字典
   
   
user_email = {}
for user in users_list:
if user.email:
user_email[user.name] = user.email
使用字典推导式
   
   
user_email = {user.name: user.email
for user in users_list if user.email}
和list的差不多还是很好理解的,多多使用效率提高


sets(集合)
(1)使用集合的数学操作
交并补 脑补高中知识
   
   
def get_both_popular_and_active_users():
# Assume the following two functions each return a
# list of user names
most_popular_users = get_list_of_most_popular_users()
most_active_users = get_list_of_most_active_users()
popular_and_active_users = []
for user in most_active_users:
if user in most_popular_users:
popular_and_active_users.append(user)
set() 将list->set
   
   
def get_both_popular_and_active_users():
# Assume the following two functions each return a
# list of user names
return(set(
get_list_of_most_active_users()) & set(get_list_of_most_popular_users()))
(2)使用set推导式生成sets
其他语法中没有的推导式经常被忽视。
   
   
users_first_names = set()
for user in users:
users_first_names.add(user.first_name)
推导式:
   
   
users_first_names = {user.first_name for user in users}
(3)set可以用来去重
   
   
unique_surnames = []
for surname in employee_surnames:
if surname not in unique_surnames:
unique_surnames.append(surname)
    
    
unique_surnames = set(employee_surnames)
都是一些提高代码效率的小技巧。

元组
(1)使用命名元组namedtuple
   
   
# Assume the 'employees' table has the following columns:
# first_name, last_name, department, manager, salary, hire_date
def print_employee_information(db_connection):
db_cursor = db_connection.cursor()
results = db_cursor.execute('select * from employees').fetchall()
for row in results:
# It's basically impossible to follow what's getting printed
print(row[1] + ', ' + row[0] + ' was hired '
'on ' + row[5] + ' (for $' + row[4] + ' per annum)'
' into the ' + row[2] + ' department and reports to ' + row[3])
    
    
from collections import namedtuple
EmployeeRow = namedtuple('EmployeeRow', ['first_name',
'last_name', 'department', 'manager', 'salary', 'hire_date'])
EMPLOYEE_INFO_STRING = '{last}, {first} was hired on {date} \
${salary} per annum) into the {department} department and reports to \
ager}'
def print_employee_information(db_connection):
db_cursor = db_connection.cursor()
results = db_cursor.execute('select * from employees').fetchall()
for row in results:
employee = EmployeeRow._make(row)
# It's now almost impossible to print a field in the wrong place
print(EMPLOYEE_INFO_STRING.format(
last=employee.last_name,
first=employee.first_name,
date=employee.hire_date,
salary=employee.salary,
department=employee.department,
manager=employee.manager))
(2)使用_做占位符,里面的数据会被忽视掉
   
   
(name, age, temp, temp2) = get_user_info(user)
if age > 21:
output = '{name} can drink!'.format(name=name)
# "Wait, where are temp and temp2 being used?"
_用来代替变量,优化啊
   
   
(name, age, _, _) = get_user_info(user)
if age > 21:
output = '{name} can drink!'.format(name=name)
# "Clearly, only name and age are interesting"
(3)使用元组解析数据
   
   
list_from_comma_separated_value_file = ['dog', 'Fido', 10]
animal = list_from_comma_separated_value_file[0]
name = list_from_comma_separated_value_file[1]
age = list_from_comma_separated_value_file[2]
output = ('{name} the {animal} is {age} years old'.format(
animal=animal, name=name, age=age))
很常用吧:
   
   
list_from_comma_separated_value_file = ['dog', 'Fido', 10]
(animal, name, age) = list_from_comma_separated_value_file
output = ('{name} the {animal} is {age} years old'.format(
animal=animal, name=name, age=age))
(4)使用元组来返回函数的多个值
   
   
from collections import Counter
STATS_FORMAT = """Statistics:
Mean: {mean}
Median: {median}
Mode: {mode}"""
def calculate_mean(value_list):
return float(sum(value_list) / len(value_list))
def calculate_median(value_list):
return value_list[int(len(value_list) / 2)]
def calculate_mode(value_list):
return Counter(value_list).most_common(1)[0][0]
values = [10, 20, 20, 30]
mean = calculate_mean(values)
median = calculate_median(values)
mode = calculate_mode(values)
print(STATS_FORMAT.format(mean=mean, median=median,
mode=mode))
这个来优化一些函数挺好用。
   
   
from collections import Counter
STATS_FORMAT = """Statistics:
Mean: {mean}
Median: {median}
Mode: {mode}"""
def calculate_staistics(value_list):
mean = float(sum(value_list) / len(value_list))
median = value_list[int(len(value_list) / 2)]
mode = Counter(value_list).most_common(1)[0][0]
return (mean, median, mode)
(mean, median, mode) = calculate_staistics([10, 20, 20, 30])
print(STATS_FORMAT.format(mean=mean, median=median, mode=mode))
同学们应该都能想到这个





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值