Page one : python基礎(chǔ)
1.請(qǐng)注意,保存數(shù)據(jù)時(shí)絕對(duì)不能用Word和Windows自帶的記事本掸掸。Word保存的不是純文本文件,而記事本會(huì)自作聰明地在文件開(kāi)始的地方加上幾個(gè)特殊字符(UTF-8 BOM)蹭秋,結(jié)果會(huì)導(dǎo)致程序運(yùn)行出現(xiàn)莫名其妙的錯(cuò)誤扰付。
2.Python提供了一個(gè)input(),可以讓用戶輸入字符串仁讨,并存放到一個(gè)變量里
3.python3除法定義
"/" 除法計(jì)算結(jié)果是浮點(diǎn)數(shù)
"http://"羽莺,稱為地板除,兩個(gè)整數(shù)的除法仍然是整數(shù)
4.只有1個(gè)元素的tuple定義時(shí)必須加一個(gè)逗號(hào)‘,’洞豁,來(lái)消除歧義
>>> t = (1,)
>>> t
(1,)
5.“非零數(shù)值盐固、非空字符串、非空l(shuí)ist等”== True,否則為False
6.數(shù)據(jù)類(lèi)型檢查可以用內(nèi)置函數(shù)isinstance()實(shí)現(xiàn)
7.定義可變參數(shù)和定義一個(gè)list或tuple參數(shù)相比族跛,僅僅在參數(shù)前面加了一個(gè)*號(hào)闰挡。在函數(shù)內(nèi)部,參數(shù)numbers接收到的是一個(gè)tuple礁哄,因此长酗,函數(shù)代碼完全不變。但是桐绒,調(diào)用該函數(shù)時(shí)夺脾,可以傳入任意個(gè)參數(shù),包括0個(gè)參數(shù):
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
>>> calc(1, 2)
5
>>> calc()
0
8.for循環(huán)作用在可迭代對(duì)象上
collections模塊的Iterable可判斷對(duì)象是否可迭代茉继。
python內(nèi)置的isinstance(data, data_type)方法判斷數(shù)據(jù)是否為給定的數(shù)據(jù)類(lèi)型
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整數(shù)是否可迭代
False
9.enumerate()函數(shù)可以把一個(gè)list變成索引-元素對(duì)
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
10.列表生成式(List comprehension)是Python內(nèi)置的非常簡(jiǎn)單卻強(qiáng)大的可以用來(lái)創(chuàng)建list的生成式
寫(xiě)列表生成式時(shí)咧叭,把要生成的元素x * x放到前面,后面跟for循環(huán)烁竭,就可以把list創(chuàng)建出來(lái)
>>>[x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for循環(huán)后面還可以加上if判斷菲茬,這樣我們就可以篩選出僅偶數(shù)的平方:
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
用兩層循環(huán),可以生成全排列:
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
11.生成器(generator)派撕,一邊循環(huán)一遍計(jì)算出后續(xù)的元素
create method1:把一個(gè)列表生成式的[]改成()
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
通過(guò)next()函數(shù)可以獲得生成器的下一個(gè)返回值
>>> next(g)
0
>>> next(g)
1
>>> for i in g:
>>> print(i)
create method2:如果一個(gè)函數(shù)定義中包含yield關(guān)鍵字婉弹,那么這個(gè)函數(shù)就不再是一個(gè)普通函數(shù),而是一個(gè)generator
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n += 1
return 'done'
調(diào)用generator時(shí)终吼,首先生成一個(gè)generator對(duì)象镀赌,然后用next()函數(shù)不斷獲得下一個(gè)返回值
def odd():
print 'step1'
yield 1
print 'step2'
yield(3)
print 'step3'
yield(5)
>>> o = odd()
>>> next(o)
step1
1
>>> next(o)
step2
3
>>> next(o)
step3
5
>>> next(o)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
odd不是普通函數(shù),而是generator际跪,在執(zhí)行過(guò)程中商佛,遇到y(tǒng)ield就中斷喉钢,下次又繼續(xù)執(zhí)行。執(zhí)行3次yield后良姆,已經(jīng)沒(méi)有yield可以執(zhí)行了肠虽,所以,第4次調(diào)用next(o)就報(bào)錯(cuò)歇盼。
但是用for循環(huán)調(diào)用generator時(shí)舔痕,發(fā)現(xiàn)拿不到generator的return語(yǔ)句的返回值。如果想要拿到返回值豹缀,必須捕獲StopIteration錯(cuò)誤,返回值包含在StopIteration的value中:
>>> for n in fib(6):
... print(n)
...
1
1
2
3
5
8
>>> g = fib(6)
>>> while True:
... try:
... x = next(g)
... print('g:', x)
... except StopIteration as e:
... print('Generator return value:', e)
... break
...
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done
12.迭代器
iter()函數(shù)可實(shí)現(xiàn)將可迭代對(duì)象Iterable(聚集對(duì)象list,tuple,set,str,dict)轉(zhuǎn)換為迭代器iterator(數(shù)據(jù)流慨代,提前不可知數(shù)據(jù)長(zhǎng)度邢笙,不斷調(diào)用next()返回值);
python的for循環(huán)本質(zhì)上通過(guò)不斷調(diào)用next()函數(shù)實(shí)現(xiàn)
iterator是惰性的侍匙,只有在需要返回下一個(gè)數(shù)據(jù)時(shí)它才會(huì)進(jìn)行計(jì)算
for x in range(10):
pass
it = iter(list(range(11)))
# 循環(huán)
while True:
try:
x = next(it)
except StopIteration:
break