内容简介:Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。要写出 Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,Github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,这里小明收集了一些常见的 Pythonic 写法,帮助你养成写优秀代码的习惯。
Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。
要写出 Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,Github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,这里小明收集了一些常见的 Pythonic 写法,帮助你养成写优秀代码的习惯。
python技巧
序列解包
a, *rest = [1, 2, 3] # a = 1, rest = [2, 3] a, *middle, c = [1, 2, 3, 4] # a = 1, middle = [2, 3], c = 4
遍历列表以及索引
##不推荐
items = 'zero one two three'.split()
# method 1
i = 0
for item in items:
print i, item
i += 1
# method 2
for i in range(len(items)):
print i, items[i]
##推荐
items = 'zero one two three'.split()
for i, item in enumerate(items):
print i, item
字典get和setdefault方法
##不推荐
navs = {}
for (portfolio, equity, position) in data:
if portfolio not in navs:
navs[portfolio] = 0
navs[portfolio] += position * prices[equity]
##推荐
navs = {}
for (portfolio, equity, position) in data:
# 使用 get 方法
navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]
# 或者使用 setdefault 方法
navs.setdefault(portfolio, 0)
navs[portfolio] += position * prices[equity]
遍历列表以及索引
##不推荐
items = 'zero one two three'.split()
# method 1
i = 0
for item in items:
print i, item
i += 1
# method 2
for i in range(len(items)):
print i, items[i]
##推荐
items = 'zero one two three'.split()
for i, item in enumerate(items):
print i, item
列表推导-嵌套
##不推荐
for sub_list in nested_list:
if list_condition(sub_list):
for item in sub_list:
if item_condition(item):
# do something...
##推荐
gen = (item for sl in nested_list if list_condition(sl)
for item in sl if item_condition(item))
for item in gen:
# do something...
循环嵌套
##不推荐
for x in x_list:
for y in y_list:
for z in z_list:
# do something for x & y
##推荐
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
# do something for x, y, z
中间结果尽量使用imap/ifilter代替map/filte
##不推荐 reduce(rf, filter(ff, map(mf, a_list))) ##推荐 from itertools import ifilter, imap reduce(rf, ifilter(ff, imap(mf, a_list))) *lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。
使用any/all函数
##不推荐
found = False
for item in a_list:
if condition(item):
found = True
break
if found:
# do something if found...
##推荐
if any(condition(item) for item in a_list):
# do something if found...
属性(property)
##不推荐
class Clock(object):
def __init__(self):
self.__hour = 1
def setHour(self, hour):
if 25 > hour > 0: self.__hour = hour
else: raise BadHourException
def getHour(self):
return self.__hour
##推荐
class Clock(object):
def __init__(self):
self.__hour = 1
def __setHour(self, hour):
if 25 > hour > 0: self.__hour = hour
else: raise BadHourException
def __getHour(self):
return self.__hour
hour = property(__getHour, __setHour)
使用 with 忽视异常(仅限 Python 3)
##不推荐
try:
os.remove("somefile.txt")
except OSError:
pass
##推荐
from contextlib import ignored # Python 3 only
with ignored(OSError):
os.remove("somefile.txt")
使用 with 处理加锁
##不推荐
import threading
lock = threading.Lock()
lock.acquire()
try:
# 互斥操作...
finally:
lock.release()
##推荐
import threading
lock = threading.Lock()
with lock:
# 互斥操作...
使用占位符
filename = 'foobar.txt'
basename, _, ext = filename.rpartition('.')
链式比较
# 不推荐
if age > 18 and age < 60:
print("young man")
# 推荐
if 18 < age < 60:
print("young man")
>>> False == False == True
False
<.>
和 <.?>
有什么区别
<.>
这种匹配称作贪心匹配 <.?>
称作非贪心匹配
Python里面search()和match()的区别
match()函数只检测RE是不是在string的开始位置匹配, search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none
如何用Python来进行查询和替换一个文本字符串?
可以使用 sub()
方法来进行查询和替换,sub方法的格式为: sub(replacement, string[, count=0])
- replacement是被替换成的文本
- string是需要被替换的文本
- count是一个可选参数,指最大被替换的数量
import re p = re.compile(’(blue|white|red)’) print(p.sub(’colour’,'blue socks and red shoes’)) print(p.sub(’colour’,'blue socks and red shoes’, count=1))
subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量
import re p = re.compile(’(blue|white|red)’) print(p.subn(’colour’,'blue socks and red shoes’)) print(p.subn(’colour’,'blue socks and red shoes’, count=1))
有两个序列a,b,大小都为n,序列元素的值任意整形数
无序;要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小。
将两序列合并为一个序列,并排序,为序列Source
拿出最大元素Big,次大的元素Small
在余下的序列S[:-2]进行平分,得到序列max,min
将Small加到max序列,将Big加大min序列,重新计算新序列和,和大的为max,小的为min。
def mean( sorted_list ): if not sorted_list: return (([],[])) big = sorted_list[-1] small = sorted_list[-2] big_list, small_list = mean(sorted_list[:-2]) big_list.append(small) small_list.append(big) big_list_sum = sum(big_list) small_list_sum = sum(small_list) if big_list_sum > small_list_sum: return ( (big_list, small_list)) else: return (( small_list, big_list)) tests = [ [1,2,3,4,5,6,700,800], [10001,10000,100,90,50,1], range(1, 11), [12312, 12311, 232, 210, 30, 29, 3, 2, 1, 1] ] for l in tests: l.sort() print print “Source List: ”, l l1,l2 = mean(l) print “Result List: ”, l1, l2 print “Distance: ”, abs(sum(l1)-sum(l2)) print ‘-*’*40
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Go语言学习技巧之如何合理使用Pool
- cURL工具的使用技巧
- slice的一些使用技巧
- 分享一些 Broadcast 使用技巧
- AndroidStudio使用技巧-debug篇
- PyCharm/IDEA 使用技巧总结
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Numerical Linear Algebra
Lloyd N. Trefethen、David Bau III / SIAM: Society for Industrial and Applied Mathematics / 1997-06-01 / USD 61.00
Numerical Linear Algebra is a concise, insightful, and elegant introduction to the field of numerical linear algebra.一起来看看 《Numerical Linear Algebra》 这本书的介绍吧!