【珍藏】積攢的高逼格Python程式碼,持續更新中......
阿新 • • 發佈:2018-11-17
用Python程式設計很久了,總感覺寫的很low,可不能總這樣呢。程式設計師逼格很重要,特別是以後還得不斷進階。於是學習一下別人Pythonic的風格,以備不時之需.............
1.簡潔的編碼彙總
1.1 快速生成字典
>>> dict(zip('張李王','三四五'))
{'張': '三', '李': '四', '王': '五'}
>>> dict(zip(['張','李','王'],['三','四','五']))
{'張': '三', '李': '四', '王': '五'}
1.2寫出類似Java中的三目表示式
def assess(score):
return 'A' if score>=90 else 'Keep trying!'
>>> assess(91)
'A'
1.3列表推倒式
>>> lists = ((1,'zhangsan'),(2,'lisi'),(3,'wangwu'))
>>> {x[0]:x[1] for x in lists}
{1: 'zhangsan', 2: 'lisi', 3: 'wangwu'}
1.4字典遍歷
>>> item = {'zhangsan':'177','lisi':'172','wangwu':'180'} >>> find_high = {k:v for k,v in item.items() if v=='180'} >>> find_high {'wangwu': '180'}
1.5給字典新增欄位,**動態新增的用法
>>> item = {'zhangsan': '177', 'lisi': '172', 'wangwu': '180'}
>>> args = {'simon':'169'}
>>> item = dict(item,**args)
>>> item
{'zhangsan': '177', 'lisi': '172', 'wangwu': '180', 'simon': '169'}
1.6帶條件的列表表示式
>>> [x for x in range(20) if x%2==0 and x%5==0] [0, 10] >>> [x+1 if x<5 else x-1 for x in range(10)] [1, 2, 3, 4, 5, 4, 5, 6, 7, 8]
2.內建函式
2.1lambda和filter搭配,過濾查詢
>>> def f(x):
return True if x == 1 else False
>>> list(filter(lambda x: f(x), [-1, 0, 1]))
[1]
2.2迭代器__iter__
class My_Iteration(object):
def __init__(self,step):
self.step = step
##next 返回容器的下一個專案
def next(self):
if self.step == 0:
raise StopIteration
self.step -= 1
def __iter__(self):
return self
2.3裝飾器
def deco_maker(arg):
def newDemo(func):
print(func, arg)
return newDemo
return newDemo
@deco_maker(deco_args)
def foo():pass
foo()
2.4with語句,與codecs搭配使用解決編碼問題
with codecs.open(fname,'r',encoding='utf-8') as f:
for line in f:
print(line)
2.5生成器:當需要返回一個序列或者在迴圈中執行的函式時就應考慮用生成器,區別於return
def generator(values):
for value in values:
print ('get value:%s' %value)
yield value ##這裡生成的是一個生成器,可用java對比思考看下
2.6 __call__:模擬函式的行為
class demo():
def __init__(self):
pass
def __call__(self,x):
return "value is:%s"%x
>>> d = demo()
>>> d(100)
'value is:100'
2.7私有方法:不能直接呼叫,需要單獨構造方法使用
>>> class Dog():
def __eat(self):
print("狗吃屎")
def find(self,food):
if food =='junk':
self.__eat()
else:
print("dog eat:"%food)
>>> Dog().find('junk')
狗吃屎
3.實用的包
3.1 heapq
>>> import heapq
>>> numbers = [100,80,24,567,787,523,45,65767]
>>> heapq.nlargest(5,numbers)
[65767, 787, 567, 523, 100]
>>> heapq.nsmallest(5,numbers)
[24, 45, 80, 100, 523]
3.2round
>>> round(3.1415926,2)
3.14
>>> round(3.1415926,0)
3.0
>>> round(3.1415926)
3
3.3grequests
import grequests
url = “http://www.baidu.com”
times = 1000
def get_ip_parallel():
reqs = (grequests.get(url) for i in range(times))
respons = grequests.map(reqs)
contents= [resp.text for resp in respons if resp.status_code == 200]
3.4requests_html
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('http://www.baidu.com/')
# 獲取頁面上的所有連結。
all_links = r.html.links
print(all_links)
3.5toapi
from toapi import XPath, Item, Api
from toapi import Settings
class MySettings(Settings):
web = {
"with_ajax": False
}
api = Api('https://news.ycombinator.com/', settings=MySettings)
class Post(Item):
url = XPath('//a[@class="storylink"]/@href')
title = XPath('//a[@class="storylink"]/text()')
class Meta:
source = XPath('//tr[@class="athing"]')
route = {'/news?page=:page':'/news?p=:page'}
class Page(Item):
next_page = XPath('//a[@class="morelink"]/@href')
class Meta:
source = None
route = {'/news?page=:page':'/news?p=:page'}
def clean_next_page(self, next_page):
return "http://127.0.0.1:5000/" + str(next_page)
api.register(Post)
api.register(Page)
api.serve()