關(guān)于獨(dú)立的程序:
我們可以將編寫的代碼放到一個(gè)文本里,并將文件名命名為xxx.py的形式。如果想要運(yùn)行程序,直接在終端或者命令終端輸入 python xxx.py。
命令行參數(shù)
我們編寫文件test.py,包含下面兩行代碼:
import sys print('Program arguments:', sys.argv)
下面是我們在shell環(huán)境下運(yùn)行這段程序:
python test.py ('Program arguments:', ['test.py']) python test.py rtcfvgbh fgh ('Program arguments:', ['test.py', 'rtcfvgbh', 'fgh'])
模塊和import語句
一個(gè)模塊僅僅是Python代碼的一個(gè)文件,是一個(gè)不帶.py擴(kuò)展的文件的文件名。引用其他模塊的代碼時(shí)使用import語句,被引用模塊種的代碼和變量對該程序可見。
導(dǎo)入模塊
下面是一個(gè)小栗子,主程序輸出報(bào)告,一個(gè)單獨(dú)的具有單個(gè)函數(shù)額度模塊返回天氣的描述。
主程序:命名為weatherman.py
import report description=report.get_description() print("Today's weather:", description)
天氣模塊的代碼:
def get_description(): """Return random weather, just like the pros""" from random import choice possibilities = ['rain', 'snow', 'sleet', 'fog', 'sun', 'who knows'] return choice(possibilities)
我們在兩個(gè)不同的地方使用了 import:
- 主程序 weatherman.py 導(dǎo)入模塊 report;
- 在模塊文件 report.py 中,函數(shù)get_description() 從 Python 標(biāo)準(zhǔn)模塊 random 導(dǎo)入函數(shù) choice。
我們以兩種不同的方式使用了 import: - 主程序調(diào)用 import report,然后運(yùn)行 report.get_description();
- report.py 中 的 get_description() 函 數(shù) 調(diào) 用 from random import choice, 然 后 運(yùn) 行 choice(possibilities)。
當(dāng)導(dǎo)入整個(gè)模塊的時(shí)候,需要把report. 作為get_description()的前綴。在這個(gè) import 語句之后,只要在名稱前加 report.,report.py 的所有內(nèi)容(代碼 和變量)就會(huì)對主程序可見。通過模塊名限定模塊的沖突,能夠避免命名的沖突。
當(dāng)所有代碼都在一個(gè)函數(shù)下,并且沒有其他名為choice的函數(shù),所以我們直接從random模塊導(dǎo)入函數(shù)choice()。
一般被導(dǎo)入的代碼使用多次,就應(yīng)該考慮在函數(shù)外導(dǎo)入;如果被導(dǎo)入的代碼使用有限,就在函數(shù)內(nèi)導(dǎo)入。一般建議在開頭導(dǎo)入。
使用別名導(dǎo)入模塊
我們可以對導(dǎo)入的模塊起一個(gè)方便記憶的別名:
import 模塊名 as 別名
以后在用到模塊名的地方都可以換成別名
導(dǎo)入模塊的一部分
在python種可以導(dǎo)入模塊的若干部分。每一部分都有自己的原始名字或者自己起的別名。首先,從 report 模塊中用原始名字導(dǎo)入函數(shù) get_description():
from report import get_description description = get_description() print("Today's weather:",description)
使用它的別名do_it導(dǎo)入:
from report import get_description as do_it description = get_description() print("Today's weather:",description)
包
我們可以把多個(gè)模塊組織稱文件層次,稱之為包。
許我們需要兩種類型的天氣預(yù)報(bào):一種是次日的,一種是下周的。一種可行的方式是新 建目錄 sources,在該目錄中新建兩個(gè)模塊 daily.py 和 weekly.py。每一個(gè)模塊都有一個(gè)函數(shù) forecast。每天的版本返回一個(gè)字符串,每周的版本返回包含 7 個(gè)字符串的列表。
下面是主程序和兩個(gè)模塊(函數(shù) enumerate() 拆分一個(gè)列表,并對列表中的每一項(xiàng)通過 for 循環(huán)增加數(shù)字下標(biāo))。
主程序:weather.py
from sources import daily,weekly
print("daily",daily.forecast())
print("weekly:")
for number,outlook in enumerate(weekly.forecast(),1):
print(number,outlook)
模塊1:sources/daily.py
def forecast():
'fake daily forecast'
return 'like yesterday'
模塊2:sources/weekly.py
def forecast():
"""Fake weekly forecast"""
return ['snow', 'more snow', 'sleet', 'freezing rain', 'rain', 'fog', 'hail']
除了以上兩個(gè)模塊外,還需要在包 sources目錄下添加一個(gè)文件:__init__
.py。這個(gè)文件可以是空的,但python需要它,以便把該目錄作為一個(gè)包。
Python標(biāo)準(zhǔn)庫
使用setdefault()和defaultdict()處理缺失的鍵
讀取字典中不存在的鍵的值會(huì)拋出異常。使用字典函數(shù)get()返回一個(gè)默認(rèn)值會(huì)避免異常發(fā)生。函數(shù)setdefault()類似get(),當(dāng)鍵不存在時(shí)它會(huì)在字典中添加一項(xiàng):
periodic_table = {'Hydrogen': 1, 'Helium': 2}
如果鍵不在字典中,新的默認(rèn)值會(huì)被添加進(jìn)去:
carbon = periodic_table.setdefault('Carbon', 12)
periodic_table {'Helium': 2, 'Carbon': 12, 'Hydrogen': 1}
如果試圖把一個(gè)不同的默認(rèn)值賦給已經(jīng)存在的鍵,不回改變原來的值,仍將返回初始值:
helium = periodic_table.setdefault('Helium', 947)
periodic_table {'Helium': 2, 'Carbon': 12, 'Hydrogen': 1}
defaultdict()也有同樣的用法,但是在字典創(chuàng)建的時(shí)候,對每個(gè)新的鍵都會(huì)指定默認(rèn)值。它的參數(shù)時(shí)一個(gè)函數(shù),下面的栗子,把函數(shù)int()作為參數(shù)傳入,會(huì)按照int()調(diào)用,返回整數(shù)0:
from collections import defaultdict
periodic_tab = defaultdict(int)
periodic_tab['Hycds'] = 1
periodic_tab['Lead']
periodic_tab
defaultdict(int, {'Heklc': 0, 'Hycds': 1, 'Lead': 0})
任何缺失的值都將被賦值為整數(shù)0:
函數(shù)defaultdict()的參數(shù)是一個(gè)函數(shù),它返回賦給缺失鍵的值,下面的栗子中no_idea()在需要時(shí)被執(zhí)行,返回一個(gè)值:
from collections import defaultdict
def no_idea():
return 'Hub'
bestity = defaultdict(no_idea)
bestity['A'] = 'nearjkl'
bestity['B'] = 'jvkefk'
bestity['A']
'nearjkl'
bestity['B']
'jvkefk'
bestity['C']
'Hub'
同樣可以使用函數(shù)int(),list()或者dict()返回默認(rèn)的值:int()返回0,list()返回空列表([ ]),dict()返回空字典({ })。如果你刪掉該函數(shù)參數(shù),新建的初始值會(huì)被設(shè)置為None。
也可以使用lambda來定義我們的默認(rèn)值:
bestiary = defaultdict(lambda: 'Huh?')
bestity['C']
'HHub'
使用int是一種定義計(jì)數(shù)器的方式:
from collections import defaultdict
food_counter = defaultdict(int)
for food in ['spam','spam','eggs','spam']:
food_counter[food]+=1
for food,count in food_counter.items():
print(food,count)
結(jié)果:
spam 3
eggs 1
上面的栗子中,如果 food_counter 已經(jīng)是一個(gè)普通的字典而不是 defaultdict 默認(rèn)字典, 那每次試圖自增字典元素 food_counter[food] 值時(shí),Python 會(huì)拋出一個(gè)異常,因?yàn)槲覀儧] 有對它進(jìn)行初始化。在普通字典中,需要做額外的工作,如下所示:
dict_counter = {}
for food in ['spam','spam','eggs','spam']:
...: if not food in dict_counter:
...: dict_counter[food] = 0
...: dict_counter[food] += 1
for food,count in dict_counter.items():
...: print(food,count)
結(jié)果:
spam 3
eggs 1
在上面的栗子中,我們先創(chuàng)建一個(gè)空的字典,然后判斷鍵時(shí)候在字典中,如果不在,設(shè)置鍵值為0,如果在將鍵值加1(肯定事先都不在)。最后遍歷字典。
使用Counter()計(jì)數(shù)
python中有一個(gè)標(biāo)準(zhǔn)計(jì)數(shù)器:Counter()
from collections import Counter
breakfast = ['spam','spam','eggs','spam']
breakfas_counter = Counter(breakfast)
breakfas_counter
Counter({'eggs': 1, 'spam': 3})
函數(shù)most_common()以降序返回所有元素,如果給定一個(gè)數(shù)字,會(huì)返回該數(shù)字前的元素:
breakfas_counter.most_common()
[('spam', 3), ('eggs', 1)]
breakfas_counter.most_common(1)
[('spam', 3)]
也可以組合計(jì)數(shù)器,下面先創(chuàng)建一個(gè)列表lunch和一個(gè)計(jì)數(shù)器lunch_counter:
lunch = ['eggs','eggs','bacon']
lunch_counter = Counter(lunch)
lunch_counter
Counter({'bacon': 1, 'eggs': 2})
第一種組合方式是使用 +:
>breakfas_counter + lunch_counter
Counter({'bacon': 1, 'eggs': 3, 'spam': 3})
第二種組合方式是使用 -:查看早餐有午餐沒有
>breakfas_counter - lunch_counter
Counter({'spam': 3})
第三種組合方式是使用交集運(yùn)算符 & 得到兩者共有的項(xiàng):
>breakfas_counter & lunch_counter
Counter({'eggs': 1})
兩者的交集通過取兩者中的較小計(jì)數(shù)。
第四種組合方式是使用并集運(yùn)算符 | 得到所有元素:
>breakfas_counter | lunch_counter
Counter({'bacon': 1, 'eggs': 2, 'spam': 3})
兩者的并集通過取兩者中較大的計(jì)數(shù)。
使用有序字典OrderedDict()按鍵排序
一個(gè)字典中鍵的順序是不可預(yù)知的,字典返回的數(shù)據(jù)順序和添加的順序可能不一致,有序字典OrderedDict()記憶字典鍵添加的順序,然后從一個(gè)迭代器按照相同的順序返回。試著用元組(鍵,值)創(chuàng)建一個(gè)有序字典:
from collections import OrderedDict
quotes = OrderedDict([('Moe','bhfsnzkml'),('Laary','Oww'),('Curly','ebanj')])
for stooge in quotes:
print(stooge)
Moe
Laary
Curly
雙端隊(duì)列:棧+隊(duì)列
deque是一個(gè)雙端隊(duì)列,同時(shí)具有棧和隊(duì)列的特征。他可以從序列的任何一端添加和刪除項(xiàng)。現(xiàn)在,我們從一個(gè)詞的兩端掃向中間,判斷是否為回文。函數(shù)popleft()去掉最左邊的項(xiàng)并返回該項(xiàng),pop()去掉最右邊的項(xiàng)并返回該項(xiàng)。從兩邊一直向中間掃描,只要兩端 的字符匹配,一直彈出直到到達(dá)中間:
def palindrome(word):
from collections import deque
dq = deque(word)
while len(dq) > 1 :
if dq.popleft() != dq.pop():
return False
return True
palindrome('a')
True
palindrome('anmmna')
True
palindrome('anmdcds')
False
palindrome('')
True
list = ['a','b','c']
palindrome(list)
False
list = ['a','b','a']
palindrome(list)
True
使用itertools迭代代碼結(jié)構(gòu)
itertools包含特殊用途的迭代器函數(shù)。在for...in循環(huán)中調(diào)用迭代函數(shù),每次會(huì)返回一項(xiàng),并記住當(dāng)前調(diào)用的狀態(tài)。
即使chain()的參數(shù)是單個(gè)迭代對象,它也會(huì)使用參數(shù)進(jìn)行迭代:
import itertools
for item in itertools.chain([1,2],['a','b'],{1:'a',2:'b'}):
print(item)
1
2
a
b
1
2
cycle()是一個(gè)在它的參數(shù)之間循環(huán)的無限迭代器:
import itertools
for item in itertools.cycle([1,2]):
print(item)
1
2
1
2
友情提示,上面小栗子會(huì)永無止境,要盡快結(jié)束
accumulate()計(jì)算累積的的值。默認(rèn)的話,它的計(jì)算是累加和:
import itertools
for item in itertools.accumulate([1,2,3,4]):
print(item)
1
3
6
10
可以把一個(gè)函數(shù)作為accumulate()的第二個(gè)參數(shù),代替默認(rèn)的加法函數(shù)。這個(gè)參數(shù)函數(shù)應(yīng)該接受兩個(gè)參數(shù),返回單個(gè)結(jié)果。下面的栗子是計(jì)算乘積:
import itertools
def multiply(a,b):
return a * b
for item in itertools.accumulate([1,2,3,4],multiply):
print(item)
1
2
6
24
使用pprint()友好輸出
之前的栗子中都用print()(或者在交互式解釋器中用變量名)打印輸出。有時(shí)輸出結(jié)果的可讀性差,我們有一個(gè)友好的輸出函數(shù):pprint()。
In [1]: from pprint import pprint
In [2]: from collections import OrderedDict
In [3]: quotes = OrderedDict([ ('Moe','A djnk ndk'), ('Larry','Oww'), ('Curry','jfnkl'), ])
In [4]: print(quotes)
OrderedDict([('Moe', 'A djnk ndk'), ('Larry', 'Oww'), ('Curry', 'jfnkl')])
In [5]: pprint(quotes)
OrderedDict([('Moe', 'A djnk ndk'), ('Larry', 'Oww'), ('Curry', 'jfnkl')])
注:本文內(nèi)容來自《Python語言及其應(yīng)用》歡迎購買原書閱讀