前段時間在碼農周刊上看到了一個不錯的學習Python的網站(Code Cademy),不是枯燥的說教,而是類似于游戲世界中的任務系統,一個一個的去完成。一做起來就發現根本停不下來,歷經10多個小時終于全部完成了,也相應的做了一些筆記。過段時間準備再做一遍,更新下筆記,并加深了解。
name = raw_input("What is your name")
這句會在console要求用戶輸入string,作為name的值。邏輯運算符順序:
not>and>or
dir(xx)
: sets xx to a list of thingslist
a = []
a.insert(1,"dog") # 按順序插入,原有順序會依次后移
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
只要循環正常退出(沒有碰到break什么的),else就會被執行。print 和 逗號
word = "Marble"
for char in word:
print char,
這里“,”保證了輸出都在同一行
- for循環中的index
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are: '
for index, item in enumerate(choices):
print index, item
enumerate可以幫我們為被循環對象創建index
zip能創建2個以上lists的pair,在最短的list的end處停止。
善用逗號
a, b, c = 1, 2, 3
a, b, c = string.split(':')
善用逗號2
print a, b
優于print a + " " + b
,因為后者使用了字符串連接符,可能會碰到類型不匹配的問題。List分片
活用步長的-1:
lists = [1,2,3,4,5];
print lists[::-1]
輸出結果:[5,4,3,2,1]
- filter 和 lambda
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
會把符合條件的值給留下,剩下的丟棄。打印出[0, 3, 6, 9, 12, 15]
-
bit operation
-
print 0b111
#7, 用二進制表示10進制數 -
bin()
函數,返回二進制數的string形式;類似的,oct()
,hex()
分別返回八進制和十六進制數的string。 -
int("111",2)
,返回2進制111的10進制數。
-
-
類的繼承和重載
- 可以在子類里直接定義和父類同名的方法,就自動重載了。
- 如果子類已經定義了和父類同名的方法,可以直接使用
super
來調用父類的方法,例如
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) - 寫文件語法
f.write(something)
。這里注意something一定要為string類型,可以用str()強制轉換。不然會寫入報錯。 - 讀全文件非常簡單,直接
f.read()
就好。 - 如果要按行讀文件,直接
f.readline()
會讀取第一行,再調用一次會讀取第二行,以此類推。 - 讀或寫完文件后,一定要記得
f.close()
。 - 自動close file:
-
with open("text.txt", "w") as textfile:
textfile.write("Success!")
`with`和`as`里有內嵌的方法`__enter__()`和`__exit__()`,會自動幫我們close file。
7) 檢查文件有沒有被關閉,`f.closed`。
- List Comprehensions
Python支持便捷的完成List的表達式,例如原代碼:
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)