【珍藏】积攒的高逼格Python代码,持续更新中......

    用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()

 

展开阅读全文

没有更多推荐了,返回首页