28 November, 2008

Python Idiom: dictionary

這次將介紹 dictionary 的常見用法,底下是建立 dictionary 的兩種方法
d = dict(a=1, b=2, c=3)
d = {'a': 1, 'b': 2, 'c': 3}
第一種做法不用打括號,打字會稍微快一點, 如果要用兩個 list 分別當作 dictionary 的 keys 跟 values, 可以利用 zip() 這個函式,例如
names = ['a', 'b', 'c']
counts = [1, 2, 3] 
d = dict(zip(names, counts))

19 November, 2008

Python Idiom: map, filter

這次我將介紹兩個跟 functional programming 有關的函式 map 及 filter。 假設我想把 list 中每一個元素平方之後放到一個新的 list,最直接的做法是
items = [1,2,3,4,5]
result = []
for i in items:
     result.append(i*i)
map 提供了另一種方法
def square(x):
     return x*x
result = map(square, items)
map 的第一個參數是函式,第二個參數是序列, 而傳回值則是將輸入的函式套用到輸入序列的每一項元素所形成的新序列。 其實還可以寫得更短
result = map(lambda x: x*x, items)
上面例子中的 lambda x: x*x 定義了一個無名函式,效果就如同前面定義的 square()。

06 November, 2008

推薦網站:The Big Picture

The Big Pictureboston.com 下的一個 photo blog,意在提供高品質令人驚豔的影像包含了當前的事件, 少為人知的故事,還有任何有趣的事情。 底下列出讓我印象深刻的系列:

05 November, 2008

Python Idiom: in

這次將介紹 in 這個關鍵字, in 最常出現在下面的用法
for key in d:
    print key
其中 d 的型態可以是 list, tuple, set, string, dictionary 等。 要檢查一個字串是否含有某子字串,通常會想到下面的做法
sentence = "fly me to the moon"
if sentence.find("fly") != -1:
     print "successful"
其實更好的方法是用 in
if "fly" in sentence:
     print "successful"
是不是更好閱讀,打字也更快呢?

04 November, 2008

Python Idiom: join

如果要將一個 list 中的所有字串接起來 ,一般的做法是
items = ['red', 'blue', 'green', 'yellow']

result = ''
for s in items:
    result += s
Python 提供了一個更有效率的解法
result = ''.join(items)
如果字串中間要用逗號跟空白做分隔時,只要改成
result = ', '.join(items)
單括號內的字串就是隔開 items 元素的分隔物, 所以如果單括號內是空的,就表示沒有分隔物。 底下介紹上述技巧的應用

03 November, 2008

Python Idiom: list comprehensions

寫程式時常常會遇到許多的 for 跟 if,如下面的範例
numbers = [1,2,3,4,5,6]
squares = []
for n in numbers:
     if n % 2 == 0:
         squares.append(n*n)
上述程式碼將 numbers 中是偶數的元素平方之後加到 squares。利用 list comprehensions 只要一行程式碼就可以完成目的。
squares = [n*n for n in numbers if n % 2 == 0]
請注意程式的可讀性是不是並沒有因為程式碼的縮短而減少呢? 其實 list comprehensions 中可以有很多個 for 跟 很多個 if, 不過使用時要斟酌一下,如果真的有很多個 for 跟 if, 最好考慮使用一般的寫法,不然程式就會變得不易閱讀。

02 November, 2008

Python Idiom: enumerate

接續 上次 的文章,這次來介紹一個關於迴圈的技巧。 如果想要印出一個 list 的內容,Python 的標準做法是
for item in items:
     print item
但如果要同時把 item 的 index 也印出來,該怎麼做?