前段時(shí)間在碼農(nóng)周刊上看到了一個(gè)不錯(cuò)的學(xué)習(xí)Python的網(wǎng)站(Code Cademy),不是枯燥的說(shuō)教,而是類(lèi)似于游戲世界中的任務(wù)系統(tǒng),一個(gè)一個(gè)的去完成淘衙。一做起來(lái)就發(fā)現(xiàn)根本停不下來(lái)传藏,歷經(jīng)10多個(gè)小時(shí)終于全部完成了腻暮,也相應(yīng)的做了一些筆記。過(guò)段時(shí)間準(zhǔn)備再做一遍毯侦,更新下筆記哭靖,并加深了解。
name = raw_input("What is your name")
這句會(huì)在console要求用戶輸入string侈离,作為name的值试幽。邏輯運(yùn)算符順序:
not>and>or
dir(xx)
: sets xx to a list of thingslist
a = []
a.insert(1,"dog") # 按順序插入,原有順序會(huì)依次后移
a.remove(xx)
- dict
del dic_name['key']
- loop:
d = {"foo" : "bar"}
for key in d:
print d[key]
3) another way to find key: `print d.items()`
print ["O"]*5 : ['O', 'O', 'O', 'O', 'O']
join操作符:
letters = ['a', 'b', 'c', 'd']
print "---".join(letters)
輸出為a---b---c---d
while/else, for/else
只要循環(huán)正常退出(沒(méi)有碰到break什么的)卦碾,else就會(huì)被執(zhí)行铺坞。print 和 逗號(hào)
word = "Marble"
for char in word:
print char,
這里“,”保證了輸出都在同一行
- for循環(huán)中的index
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are: '
for index, item in enumerate(choices):
print index, item
enumerate可以幫我們?yōu)楸谎h(huán)對(duì)象創(chuàng)建index
zip能創(chuàng)建2個(gè)以上lists的pair洲胖,在最短的list的end處停止济榨。
善用逗號(hào)
a, b, c = 1, 2, 3
a, b, c = string.split(':')
善用逗號(hào)2
print a, b
優(yōu)于print a + " " + b
,因?yàn)楹笳呤褂昧俗址B接符绿映,可能會(huì)碰到類(lèi)型不匹配的問(wèn)題擒滑。List分片
活用步長(zhǎng)的-1:
lists = [1,2,3,4,5];
print lists[::-1]
輸出結(jié)果:[5,4,3,2,1]
- filter 和 lambda
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
會(huì)把符合條件的值給留下,剩下的丟棄叉弦。打印出[0, 3, 6, 9, 12, 15]
-
bit operation
-
print 0b111
#7, 用二進(jìn)制表示10進(jìn)制數(shù) -
bin()
函數(shù)丐一,返回二進(jìn)制數(shù)的string形式;類(lèi)似的淹冰,oct()
,hex()
分別返回八進(jìn)制和十六進(jìn)制數(shù)的string库车。 -
int("111",2)
,返回2進(jìn)制111的10進(jìn)制數(shù)樱拴。
-
-
類(lèi)的繼承和重載
- 可以在子類(lèi)里直接定義和父類(lèi)同名的方法柠衍,就自動(dòng)重載了。
- 如果子類(lèi)已經(jīng)定義了和父類(lèi)同名的方法疹鳄,可以直接使用
super
來(lái)調(diào)用父類(lèi)的方法拧略,例如
class Derived(Base):
def m(self):
return super(Derived, self).m()
- File I/O
-
f = open("a.txt", "w")
: 這里w為write-only mode,還可以是r (read-only mode) 和 r+ (read and write mode)瘪弓,a (append mode) - 寫(xiě)文件語(yǔ)法
f.write(something)
垫蛆。這里注意something一定要為string類(lèi)型,可以用str()強(qiáng)制轉(zhuǎn)換。不然會(huì)寫(xiě)入報(bào)錯(cuò)袱饭。 - 讀全文件非常簡(jiǎn)單川无,直接
f.read()
就好。 - 如果要按行讀文件虑乖,直接
f.readline()
會(huì)讀取第一行懦趋,再調(diào)用一次會(huì)讀取第二行,以此類(lèi)推疹味。 - 讀或?qū)懲晡募蠼鼋校欢ㄒ浀?code>f.close()。
- 自動(dòng)close file:
-
with open("text.txt", "w") as textfile:
textfile.write("Success!")
`with`和`as`里有內(nèi)嵌的方法`__enter__()`和`__exit__()`糙捺,會(huì)自動(dòng)幫我們close file诫咱。
7) 檢查文件有沒(méi)有被關(guān)閉,`f.closed`洪灯。
- List Comprehensions
Python支持便捷的完成List的表達(dá)式坎缭,例如原代碼:
list_origin = [1, 2, 3, 4, 5, 6]
list_new = []
for i in list_origin:
if i % 2 == 0:
list_new.append(i)
可以直接一行搞定:
list_origin = [1, 2, 3, 4, 5, 6]
list_new = [i for i in list_origin if i % 2 == 0]
Reference##
- Codecademy Python Program
(http://www.codecademy.com/zh/tracks/python)