魏泯html
童心未泯就是,又是一個飛雪連天日,我團個雪球踢着走。python
*跳轉到文章結尾*
mysql
註釋的學問程序員
Pycharm的經常使用快捷鍵正則表達式
課前學習:計算機基礎redis
字符串處理算法
python源於聖誕節,他的創造者是Guido van Rossum(賢者-龜叔)。sql
┌────────────────────────────────────────────────────────┐ │Command Prompt - python _ □ x │ ├────────────────────────────────────────────────────────┤ │>>> print("Here not a world.") │ │Here not a world. │ │>>> _ │ │ │ │ │ │ by: Asterism2012 | └────────────────────────────────────────────────────────┘
在進行Python的開發以前,首先要保證你的電腦上已經安裝了Python,但不要求必定是最新版本的。mongodb
*返回目錄再看看*
shell
在Pycharm中配置爲咱們的虛擬環境
前後點擊:file---settings---Project-----project Interpreter用的時間長了天然就會了。
(參考自《Python程序設計(第二版)》嵩天)
Python是一種計算機編程語言。計算機編程語言和咱們平常使用的天然語言有所不一樣,最大的區別就是,天然語言在不一樣的語境下有不一樣的理解,而計算機要根據編程語言執行任務,就必須保證編程語言寫出的程序決不能有歧義,因此,任何一種編程語言都有本身的一套語法,編譯器或者解釋器就是負責把符合語法的程序代碼轉換成CPU可以執行的機器碼,而後執行。——廖雪峯
編程的目的是:「使用計算機解決問題」。
while True: #在Python中,使用縮進來表示層級關係,這是很酷的一個功能 print("I miss you.")
代碼註釋在每個高級語言中都存在,用於用咱們人的語言來爲咱們寫的代碼進行標註,提升咱們代碼的可讀性,從而提升咱們協同工做的效率,以及下降咱們的維護代碼的時間成本。
#
號):# 我是一段註釋,我寫的代碼意思是這樣的
''' '''
三引號):'''我是多行註釋,我是能夠換行顯示的, 你看,我換行了'''
值得一提的是:多行註釋不能放在在列表、集合、字典中:
dic1 = { │ lis1 = [ │set1 = { '''Student dict''' │ '''New List''' │ '''New set''' 'name':'Tom', │ 1, │ 1, 'age':'18' # No │ 2 # No │ 2, # No } │] │}
上面這種寫法都是錯誤的。在容器類型的數據類型中,三引號囊括起來的內容會被視爲字符串。
可是單行註釋是被容許的:
set1 = [ # New set 1,2 ]
像這樣寫是能夠的,能夠本身打印這些變量嘗試一下。
給導入的標準包起名
from lxml import etree as e
>>>dic1 = dict() >>>set1 = set() >>>lis1 = list()
查看一下類型
>>> type(dic1) <class 'dict'> >>> type(lis1) <class 'list'> >>> type(set1) <class 'set'>
可是當a = 1;b = 1時,1這個數據所在的內存地址的引用計數爲2,名爲a,b。但咱們del b時,1這個數據的引用計數爲1,名爲a。
列表與元祖:元祖比列表更快
list = ["M","i","s","s"]
函數名其實就是指向一個函數對象的引用,徹底能夠把函數名賦給一個變量,至關於給這個函數起了一個「別名」:
max函數max()能夠接收任意多個參數,並返回最大的那個:
>>> max(1, 2) 2 >>> max(2, 3, 1, -5) 3
range(start,stop,step)
start:計數從start開始,默認爲0.
stop:計數到stop結束,但不包括stop。
step:計數跨度,默認爲1。
指定一個參數
range(8)
[0, 1, 2, 3, 4, 5, 6, 7]
指定兩個參數
range(1,15)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
指定三個參數
range(1,100,20)
[1, 21, 41, 61, 81]
支持負參數(愈來愈小)
range(-10,-20,-1)
[-10, -11, -12, -13, -14, -15, -16, -17, -18, -19]
倒序
range(100,19,-5)
[100, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20]
指定參數0
range(0)
[]
不指定參數
range()
Traceback (most recent call last):
File "", line 1, in
TypeError: range expected at least 1 arguments, got 0
range()被視爲一個range類型(範圍)的對象,使用type()函數則會看到
type(range(0))
<class 'range'>
使用help()函數則會看到
Help on class range in module builtins:
class range(object)在Python3中進行操做,不會返回列表,而是範圍對象的內容。
range(0)
range(0, 0)
range(-10,-20,-1)
range(-10, -20, -1)
range(1)
range(0, 1)
range(10,100,20)
range(10, 100, 20)
這一塊等待更新
回頭把表格更新出來,字符串
re.match()
嘗試從字符串的起始位置匹配一個模式,若是不是起始位置匹配成功的話,match()就返回Nonere.match(正則表達式)
re.search()
掃描整個字符串、返回第一個匹配到的內容
re.findall()
掃描整個字符串,以列表形式返回全部匹配目標(分組),能夠理解爲一個大的group()
re.sub() 也能夠稱做sub方法 : 用於替換字符串中的指定內容
# 普通替換 >>>result = re.sub("d+","Hi",'123 world') >>>result Hi world '''進階替換(插入) 包含源字符串自己的內容 規定原生(字符串)的r與Back slash slash(「\」)轉義來保證字符串的正確性''' >>>result = re.sub("(\d+)",r"\1 123","456") >>>result 456 123
result.group(x) #獲取正則表達式中第x個括號中的字符串內容
>>>result = re.match('.*(\d+)',"a123") >>>result.group(1) a12
>>>result = re.match('.*(\d+)',"a123") >>>result.group(1) a
re.match('Hello \$world.','Hello $world.')
正則的空白字符\s
正在更新中
建立方法的說明:
經過生成式生成
經過函數生成
經過生成式生成
generator = (i for i in range(10))
python2.7與python3.5的版本沒有區別
類型檢查type()
type(generator)
<class 'generator'>
直接打印
>>> generator <generator object <genexpr> at 0x000002962143B938>
幫助信息
Help on generator object: <genexpr> = class generator(object) ''' 譯文:生成器的幫助信息: '''
>>>datelis = ["10月{}日".format for i in range(1,32)] >>>datelis ['10月1日', '10月2日', '10月3日', '10月4日', '10月5日', '10月6日', '10月7日', '10月8日', '10月9日', '10月10日', '10月11日', '10月12日', '10月13日', '10月14日', '10月15日', '10月16日', '10月17日', '10月18日', '10月19日', '10月20日', '10月21日', '10月22日', '10月23日', '10月24日', '10月25日', '10月26日', '10月27日', '10月28日', '10月29日', '10月30日', '10月31日']
>>>dicgene = {i:i for i in range(20)} # 最常規字典推導式 >>>dicgene {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19} >>>dicgene2 = {index:i for i in enumerate(datelis)} # 常規的 用字典排序列表 >>>dicgene2 {0: '10月1日', 1: '10月2日', 2: '10月3日', 3: '10月4日', 4: '10月5日', 5: '10月6日', 6: '10月7日', 7: '10月8日', 8: '10月9日', 9: '10月10日', 10: '10月11日', 11: '10月12日', 12: '10月13日', 13: '10月14日', 14: '10月15日', 15: '10月16日', 16: '10月17日', 17: '10月18日', 18: '10月19日', 19: '10月20日', 20: '10月21日', 21: '10月22日', 22: '10月23日', 23: '10月24日', 24: '10月25日', 25: '10月26日', 26: '10月27日', 27: '10月28日', 28: '10月29日', 29: '10月30日', 30: '10月31日'}
下文的一部分time表明的是datetime類型的對象
>>>now = time.time() 1540374057.6383073
>>>time.localtime(time.time()) time.struct_time(tm_year=2018, tm_mon=10, tm_mday=24, tm_hour=17, tm_min=42, tm_sec=44, tm_wday=2, tm_yday=297, tm_isdst=0)
>>>time.strftime("%Y%m%d %H:%M:%S",time.localtime(time.time())) '20181024 18:00:21'
下文的一部分datetime 表明的是datetime類型的對象
獲取當前時間:datetime.now()
from datetime import datetime
now = datetime.now()
print(now)
2018-10-23 14:36:14.238998
獲取datetime對象的
用於格式化datetime類型的對象,返回一個str類型的對象
格式符 說明
%a 星期的英文單詞的縮寫:如星期一, 則返回 Mon
%A 星期的英文單詞的全拼:如星期一,返回 Monday
%b 月份的英文單詞的縮寫:如一月, 則返回 Jan
%B 月份的引文單詞的縮寫:如一月, 則返回 January
%c 返回datetime的字符串表示,如03/08/15 23:01:26
%d 返回的是當前時間是當前月的第幾天
%f 微秒的表示: 範圍: [0,999999]
%H 以24小時製表示當前小時
%I 以12小時製表示當前小時
%j 返回 當天是當年的第幾天 範圍[001,366]
%m 返回月份 範圍[0,12]
%M 返回分鐘數 範圍 [0,59]
%p 返回是上午仍是下午–AM or PM
%S 返回秒數 範圍 [0,61]。。。手冊說明的
%U 返回當週是當年的第幾周 以週日爲第一天
%W 返回當週是當年的第幾周 以週一爲第一天
%w 當天在當週的天數,範圍爲[0, 6],6表示星期天
%x 日期的字符串表示 :03/08/15
%X 時間的字符串表示 :23:22:08
%y 兩個數字表示的年份 15
%Y 四個數字表示的年份 2015
%z 與utc時間的間隔 (若是是本地時間,返回空字符串)
%Z 時區名稱(若是是本地時間,返回空字符串)
%% %號自己
---------------------
做者:ShomyLiu
來源:CSDN
原文:https://blog.csdn.net/shomy_liu/article/details/44141483
版權聲明:本文爲博主原創文章,轉載請附上博文連接!
使用strftime獲取當前時間的日期部分:%x
from datetime import datetime
now = datetime.now()
date = now.strftime("%x")
'10/23/18'
獲取單獨的 年 月 日 部分:datetime.year(),datetime.month(),datetime.day()
now.year
2018
now.month
10
now.day
23
strftime()能夠自定義格式化標準
now.strftime("%x %X")
'10/23/18 14:52:20'
trptime是python datetime庫中的函數,用於將一個日期字符串轉成datetime日期格式便於後期處理,使用格式爲datetime.strptime(date_string, format);格式化(format)使用的參數與上面所講的strftime()所用的格式化參數是同樣的,可是它要與字符串位置一一對應才行。
timedelta()是datetime()這個超類內置的方法,用於計算過去的時間,返回一個datetime.timedelta()類型的變量。
import datetime
>>> loseTime = datetime.timedelta(days=-1) >>> loseTime datetime.timedelta(-1) # 也能夠是一週前,你們觸類旁通吧 # >>>loseTime = datetime.timedelta(weeks=-1)
>>> nowTime = datetime.datetime.now() >>> nowTime datetime.datetime(2018, 10, 25, 18, 53, 23, 108495)
>>> that_time = nowTime+loseTime >>> that_time datetime.datetime(2018, 10, 24, 18, 53, 23, 108495) # 時間變化了!看到沒?
所謂常量就是不能變的變量,好比經常使用的數學常數π就是一個常量。在Python中,一般用所有大寫的變量名錶示常量:
PI = 3.14159265359
但事實上PI仍然是一個變量,Python根本沒有任何機制保證PI不會被改變,因此,用所有大寫的變量名錶示常量只是一個習慣上的用法,若是你必定要改變變量PI的值,也沒人能攔住你。(----來自:廖雪峯的官方網站 https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431658624177ea4f8fcb06bc4d0e8aab2fd7aa65dd95000)
*args和與**kwargs
* 和**
這兩個符號影響,而*args和**kwargs
只是約定的非強制性的。也就是說,arg和kwargs這兩個名字並非必須叫這個名字的,而*號是必須有的。*args 和**kwargs
能夠單獨使用*args和**kwargs
能夠一塊兒使用*args必須在**kwargs
前面*
會把list或者tuple分解爲一個個參數傳遞給函數**
會把dict轉成關鍵字參數* 或者**
*args
是不帶keyd容器及字符串,**kwargs
是帶‘key’的容器。*args
匹配多個元素,kwargs
匹配鍵值對。*args不定長參數案例
def func(*args):
print(args)
print(type(args))
func(1,2,'a')
# output:
(1, 2, 'a')
<class 'tuple'>
**kwargs不定長參數案例
def func(**kwargs):
print(kwargs)
print(type(kwargs))
func(a=1,b=2)
# output:
{'a': 1, 'b': 2}
<class 'dict'>
*
號進行拆包單*號拆包
list1 = [1,2,3]
print(*list1)
雙*號拆包
dict1 = {'a':1,'b':2}
def func(a,b):
print(a,b)
func(**dict1)
它用於進行檢查某一個變量的類型,但他是type()函數的高階版本。它擁有更強大的功能,同時也擁有更多的發揮空間。
檢測單個變量是否爲某個類型
dic1 = {'a':'z'}
isinstance(dic1,dict) # 這一行是判斷dic1變量是否爲字典類型
True
isinstance(dic1,tuple) # 這一行是判斷dic1變量是否爲元祖類型
False
檢測單個變量是否在所指定的類型範圍內
'''判斷dic1是不是:
整型、浮點型、字符串、列表、集合、字典、元祖類型中的一種
'''
isinstance(dic1,(int,float,str,list,set,dict,tuple))
True
'''判斷dic1是不是:
整型、浮點型、字符串、列表、集合、元祖類型中的一種
'''
isinstance(dic1,(int,float,str,list,set,tuple))
False
檢測多個變量是否在指定的類型範圍內
dic1 = {'a':'z'}
dic2 = {'c':'w'}
isinstance((dic1,dic2),(int,float,str,list,set,dict,tuple))
True
isinstance((dic1,dic2),(int,float,str,list,set,tuple))
False
最後值得一提的是,此函數在Python2.x版本和Python3.x版本中,沒有版本差別。
Python strip() 方法用於移除字符串頭尾指定的字符(默認爲空格或換行符)或字符序列。
判斷文件夾是否存在,不存在則建立
d = '新建文件夾' if not os.path.exists(d): os.mkdir(d)
__file__
print(__file__) # 不要以命令的形式執行它,告訴你,執行不了!...剛纔不是我
默認是斜槓
pth = os.path.dirname('C:/Users/DELL/Desktop/test.py') print(pth)
Console:
C:/Users/DELL/Desktop
os.path.dirname 是比較動搖的,它傳入的路徑字符串裏用的是反斜槓,它打印出來就是反斜槓。可是若是傳入的路徑字符裏用的是斜槓,它打印出來的就是斜槓。
os.path.abspath()
os.path.abspath 是很是堅決的(絕對路徑,絕對懂嗎?很是絕對)它不論你傳入的是路徑字符串勵用的是反斜槓仍是斜槓,他打印出來都是反斜槓~~~~ 額剛纔不是我。算了太晚了 該睡了。
os.path.join("C:/User/DELL/Desktop", "test.py")
import shelve f = shelve.open("shelve_test") f['info'] = "alex" f["age"] = [1,34,5,6,33,44] f["name"] = {"name":"alex","add":"sz"} f.close() f = shelve.open("shelve_test") print(f.get("info")) print(f.get("age")) print(f.get("name")) print(f['info']) print(f.values()) print(f.items()) print(f.keys())
import shelve with shelve.open("test_shelve.db") as f: f["k1"] = { "name":"zhangguojun1", "age":12, "address":"shenzhen1" } f["k4"] = ["張國軍1","張國軍2","張國軍3"] print(f["k1"]["name"]) print(f["k4"][0])
正在更新中
dict.items() 以列表返回可便利的(鍵、值)元祖數據,還是一個字典對象
for v,j in dict.items:
print(v,j)
list1 = [1,2,3] randint = random.choice(list1)
>>>import random >>>a = random.randrange(1,999) >>>a 85
今天先把Python三大特性之一的「封裝」特性放在一邊。聊一聊繼承與多態,簡單的來講,繼承與多態是體如今面向對象編程中的類編程上。
class Animals(object): # object 是 Animals的父類 def run(self,name="Animals"): print("%s are running.") class Cats(Animals): # Animals是Cats的父類 def run(self,name="Cats"): print("%s are running.") cats = Cats() # 實例化Animals 的子類 Cats cats.run() # run方法體現繼承,console: Cats are running.
# 這體現了cats的數據類型是Animals list0727 = [] print(isinstance(list0727,list)) # console:True print(isinstance(cats,Cats)) # console:True print(isinstance(cats,Animals)) # console:True
def run_twice(animals): # 這裏的形參名稱是本身定義的,能夠改爲別的名稱,可是這裏只是爲了方便咱們記憶。 animals.run() run_twice(Cats()) # console: Cats is running. '''接下來能夠體現 動態語言 的 鴨子類型: 它並不要求嚴格的繼承體系,一個對象只要「看起來像鴨子,走起路來像鴨子」,那它就能夠被看作是鴨子。 ''' class People(objects): def run(self): print("People are running.") run_twice(People()) '''在靜態語言中(例如),若是要傳入animals類型的參數,則傳入的對象必須是animals類型 或者是它的子類,不然,將沒法調用run()方法。 可是,對於Python這樣的動態語言來叔,則不須要傳入Animal類型。咱們只須要保證傳入的對象有一個run()方法就夠了。 '''
這一小節來自於「廖雪峯的官方網站」 https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431865288798deef438d865e4c2985acff7e9fad15e3000
pip install pymysql
創建數據庫鏈接,並獲取對象
db = pymysql.connect(user='root',password='mysql',db='233',charset='utf8')創建遊標
cursor = db.cursor()編寫sql語句
# 如下六個變量都是初始化過的使用遊標執行語句
cursor.excute(sql)提交事務
db.commit()
創建鏈接而且獲取到鏈接對象
myconn = pymongo.MongoClient("localhost",27017)生成數據庫
mydb = myconn["LagouWeb"]生成集合
mycoll = mydb["zhaopin"]將文檔(必須是字典類型的數據)存入集合
info = {key:value}
mycoll.insert(info)
str.split(" ",3) 表示以空格來切,字符串,將其切成列表,只切前三個(第二個參數是可選的,就是能夠不填寫)
str.startswith(" ") 表示檢查字符串是不是以指定子字符串開頭,若是是則返回 True,不然返回 False。若是參數 beg 和 end 指定值,則在指定範圍內檢查。(str.startswith(str, beg=0,end=len(string))
操做系統:windows10
爲何使用虛擬環境?搭建獨立python運行環境。防止相同包的不一樣版本之間相互衝突和覆蓋。
virtualenv是是python的虛擬環境管理器
md virtual_now(會在當前目錄建立一個名爲‘virtual_now’的子文件夾) cd virtual_now
pip install virtualenv(pip是python的包管理工具)
virtualenv --no-site-packages newenv (像建立文件夾同樣建立了一個環境目錄‘newenv’) #關於--no-site-pakeages參數#:它不會複製已存在的第三方包
使用指定Python解釋器的方式建立環境:
virtualenv -p c:\python27\python.exe venv
cd Scripts activate(激活環境)
pip install django==1.11.1
python
7.退出虛擬環境
deactivate
virtualenvwrapper能夠簡化virtualenv包的操做
pip install virtualenvwrapper-win
C:\workon Pass a name to activate one of the following virtualenvs: ==============================================================================
建立虛擬環境管理目錄(虛擬環境都會進入這個目錄中):
設置系統環境變量(WIN10的話直接新建就能夠),後面添加本身想要的虛擬環境目錄位置。
┌────────────────────────────────────────────────────────┐ │ Edit system variables _ □ x │ ├────────────────────────────────────────────────────────┤ │ ┌──────────────────────────────────┐ │ │ Variable Name(N) │ WORKON_HOME │ │ │ └──────────────────────────────────┘ │ │ ┌──────────────────────────────────┐ │ │ Variable Value(V) │ E:\virtual_now │ │ │ └──────────────────────────────────┘ │ │ ┌────────┐ ┌────────┐ │ │ │ OK │ │ Cancel │ │ │ └────────┘ └────────┘ │ └────────────────────────────────────────────────────────┘ by: Asterism
C:\mkvirtualenv Py3_django2
以指定python3環境的方式創建虛擬環境
C:\mkvirtualenv -p python3 venv
C:\workon Py3_django2
C:\lsvirtualenv
C:\deactivate
C:\cdsitepackages
C:\lssitepackages
C:\wipeenv
C:\rmvirtualenv Py3_django2
C:\cpvirtualenv Py3_django2
C:\> setvirtualenvproject Py3_django2
部分參考:
做者:lliuz
來源:CSDN
原文:https://blog.csdn.net/melpancake/article/details/54578711
版權聲明:本文爲博主原創文章,轉載請附上博文連接!
virtualenvwrapper-win is a port of Dough Hellman’s virtualenvwrapper to Windows batch scripts. (virtualenvwrapper-win是Dough Hellman開發的 windows操做系統的 批處理腳本。) Commands available: (可用命令:) add2virtualenv: add directory to the import path cdproject: change directory to the active project cdsitepackages: change to the site-packages directory cdvirtualenv: change to the $VIRTUAL_ENV directory lssitepackages: list contents of the site-packages directory lsvirtualenv: list virtualenvs mkproject: create a new project directory and its associated virtualenv mkvirtualenv: Create a new virtualenv in $WORKON_HOME rmvirtualenv: Remove a virtualenv setprojectdir: associate a project directory with a virtualenv toggleglobalsitepackages: turn access to global site-packages on/off virtualenvwrapper: show this help message whereis: return full path to executable on path. workon: list or change working virtualenvs
操做系統:Linux
sudo pip install virtualenv (安裝) sudo pip install virtualenvwrapper (打包安裝)
(python2) mkvirtualenv [環境名] (python3) mkvirtualenv -p python3 [環境名]
workon (查詢) workon [虛擬環境名] (使用) deactivate (退出虛擬環境) rmvirtualenv (刪除虛擬環境)
which python where python
pip install 包名 pip install 包名==版本號
pip uninstall 擴展報名
pip freeze pip freeze >
pip list
pip freeze > requirements.txt
pip install -r requirements.txt
國內源:
阿里雲 http://mirrors.aliyun.com/pypi/simple/
中國科技大學 https://pypi.mirrors.ustc.edu.cn/simple/
豆瓣(douban) http://pypi.douban.com/simple/
清華大學 https://pypi.tuna.tsinghua.edu.cn/simple/
pip install -i http://pypi.douban.com/simple 模塊名
若是出現不信任的報錯,則須要在命令後加上:
pip install -i http://pypi.douban.com/simple --trusted-host pypi.douban.com 模塊名
#!/usr/bin/env python與#!/usr/bin/python的區別(/bin/可執行文件)
腳本語言的第一行,++目的就是指出++,你想要你的這個++文件中的代碼用什麼可執行程序去運行++它,
#!/usr/bin/python
是告訴操做系統執行這個腳本的時候,調用/usr/bin下的python解釋器;
#!/usr/bin/env python
這種用法是爲了++防止操做系統用戶沒有將python裝在默認的/usr/bin路徑++裏。當系統看到這一行的時候,首先會到env設置裏查找python的安裝路徑,再調用對應路徑下的解釋器程序完成操做。
(#!/usr/bin/python
至關於寫死了python路徑;
#!/usr/bin/env python
會去環境設置尋找python目錄:推薦這種寫法。)
尊重版權:轉載自博客園 https://www.cnblogs.com/walk1314/p/7076853.html (Mr_Walker),如需轉載請註明出處,尊重他人的勞動成果,也尊重你本身。
time.sleep=lambda x:None '''後續代碼中調用time庫的sleep函數將不會執行原有的功能。例如,執行time.sleep(3)時,程序不會休眠3秒鐘,而是什麼都不作。括號中的x表明這個標準庫函數的本來形參。'''
return lambda x,y:x+y '''。這時,lambda函數其實是定義在某個函數內部的函數,稱之爲嵌套函數,或者內部函數。對應的,將包含嵌套函數的函數稱之爲外部函數。內部函數可以訪問外部函數的局部變量,這個特性是閉包(Closure)編程的基礎,在這裏咱們不展開。'''
filter(lambda x: x % 3 == 0, [1, 2, 3]) sorted函數。此時lambda函數用於指定對列表中全部元素進行排序的準則。例如sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x))將列表[1, 2, 3, 4, 5, 6, 7, 8, 9]按照元素與5距離從小到大進行排序,其結果是[5, 4, 6, 3, 7, 2, 8, 1, 9]。 map函數。此時lambda函數用於指定對列表中每個元素的共同操做。例如map(lambda x: x+1, [1, 2,3])將列表[1, 2, 3]中的元素分別加1,其結果[2, 3, 4]。 reduce函數。此時lambda函數用於指定列表中兩兩相鄰元素的結合條件。例如reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9])將列表[1, 2, 3, 4, 5, 6, 7, 8, 9]中的元素從左往右兩兩以逗號分隔的字符的形式依次結合起來,其結果是'1, 2, 3, 4, 5, 6, 7, 8, 9'。
一個爭議
>>>pf = lambda x:x**2 >>>pf(1) 1 >>>pf(2) 4
求幾個數之和的匿名函數
f = lambda *args:sum(args)
f(1,2,3,4)
10
filter()
函數用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。
該接收兩個參數,第一個爲函數,第二個爲序列,序列的每一個元素做爲參數傳遞給函數進行判,而後返回 True 或 False,最後將返回 True 的元素放到新列表中。
filter(function, iterable)
def is_odd(n):print()
print()函數接收不少參數,咱們須要主要學習的是sep,end,file這個三個參數;能夠在源碼中看到,他們的默認值是:
sep=' ', end='\n', file=None
sep是改變多個輸出內容的分隔符,end是改變輸出末尾的換行,file則是輸出到一個文件
# file參數指向的應該是一個文件對象 with open("new.txt","a+") as f: print("Print over.",file=f) # 這樣能夠將輸出內容打印到一個文件中去
enumrate()
遍歷索引:當遍歷一個可迭代對象時候,使用此函數能夠提供遍歷索引。
for index,name in all_name:
... print(index,name)
1 tom
2 lily
3 alice
...
在python編程時操做文件與目錄、以及使用shell命令,就須要os模塊的支持。os模塊包含廣泛的操做系統功能,與具體的平臺無關。
sms_code = "%06d" % random.randint # 生成驗證碼
from django_redis import get_redis_connection redis_conn = get_redis_connection
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, "session": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # 圖片驗證碼的redis "verify_codes": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "session"
# 使用redis的pipeline管道一次執行多個命令 pl = redis_conn.pipeline() # 保存短信驗證碼 redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPRIES, sms_code) # 保存當前的時間,只是作個記錄而已,60s過時 redis_conn.setex('sms_interval', constants.SMS_CODE_REDIS_INTERVAL, datetime.now()) # 讓管道執行命令 pl.execute()
itsdangerous(它是危險的),顧名思義。如下是來自官方網站的介紹。
(Py_Django2.0.6) C:\Users\DELL\Desktop\meiduo-email>pip install itsdangerous
>>> from itsdangerous import Signer # 導入Signer方法 >>> s = Signer('secret-key') # 實例化一個以‘secret-key’爲密鑰的<class 'itsdangerous.signer.Signer'>對象 >>> s.sign('my string') # 使用這個對象含有的密鑰 使用字符串生成簽名 b'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA' # 這一步是可逆的 >>> s.unsign('my string.wh6tMHxLgJqB6oY1uT73iMlyrOA') # 對這個簽名進行轉碼 b'my string'
它繼承了JSONWebSignatureSerializer類。
首先咱們來看生成令牌和解碼令牌的代碼: from itsdangerous import TimedJSONWebSignatureSerializer s = TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'], expires_in=3600) token = s.dumps({'confirm': 23}) data = s.loads(token) --------------------- 做者:她叫徐曉jie 來源:CSDN 原文:https://blog.csdn.net/sinat_34927324/article/details/78378911 版權聲明:本文爲博主原創文章,轉載請附上博文連接!
咱們老師的老大使用這個模塊生成了token,而且對它進行了解密。
def generate_email_verify_url(self): serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=24*60*60) # 生成token data = {'user_id': self.id, 'email': self.email} token = serializer.dumps(data).decode() verify_url = 'http://127.0.0.1:8080/success_verify_email.html?token=' + token return verify_url
解密。
@staticmethod # 類能夠直接調用 def check_email_verify_token(token): """ 檢查驗證郵件的token """ serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=300) try: data = serializer.loads(token) # 對token進行解碼 except BadData: return None else: email = data.get('email') user_id = data.get('user_id') User.objects.filter(id=user_id, email=email).update(email_active=True) return True
英[paɪ'θɒnɪk] 美[paɪ'θɒnɪk]
adj. 神諭的,預言的,大蟒似的;
Pythoner們常說,寫代碼要寫得Pythonic一些,那麼什麼是Pythonic呢?Pythonic實際上是一種編碼風格。瞧瞧這翻譯,夠酷炫的。神諭的,什麼是神諭?那是神說的話,神說話,一貫簡單簡短又充滿哲理。這就是咱們寫Python程序要達成的目標,Python代碼應該寫的簡短又精彩。
import this
就會顯示Tim Peters的The Zen of python
原文
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
翻譯
Python之禪 by Tim Peters
優美勝於醜陋(Python 以編寫優美的代碼爲目標)
明瞭勝於晦澀(優美的代碼應當是明瞭的,命名規範,風格類似)
簡潔勝於複雜(優美的代碼應當是簡潔的,不要有複雜的內部實現)
複雜勝於凌亂(若是複雜不可避免,那代碼間也不能有難懂的關係,要保持接口簡潔)
扁平勝於嵌套(優美的代碼應當是扁平的,不能有太多的嵌套)
間隔勝於緊湊(優美的代碼有適當的間隔,不要奢望一行代碼解決問題)
可讀性很重要(優美的代碼是可讀的)
即使假借特例的實用性之名,也不可違背這些規則(這些規則至高無上)
不要包容全部錯誤,除非你肯定須要這樣作(精準地捕獲異常,不寫 except:pass 風格的代碼)
當存在多種可能,不要嘗試去猜想
而是儘可能找一種,最好是惟一一種明顯的解決方案(若是不肯定,就用窮舉法)
雖然這並不容易,由於你不是 Python 之父(這裏的 Dutch 是指 Guido )
作也許好過不作,但不假思索就動手還不如不作(動手以前要細思量)
若是你沒法向人描述你的方案,那確定不是一個好方案;反之亦然(方案測評標準)
命名空間是一種絕妙的理念,咱們應當多加利用(倡導與號召)
出自:意氣相許的許
連接:https://www.jianshu.com/p/0e1f38c2c122
來源:簡書
簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。
第一象限:緊急重要·趕忙搞定
第二象限:重要,不緊急·保持關注
第三象限:緊急不重要·學會拒絕
第四象限:不緊急,不重要·靠自律
——來自知道創宇技能表
《python程序設計(第二版)》
《笨方法學Python》