[Python]利用Python特點縮短程式碼(1)
在Python中就是要享受程式碼的短小,常見的有map, reduce, filter, list comprehensions, itertools, lambda forms等。本篇會Focus在filter和list comprehensions。
List Comprehensions
就list comprehensions而言,比如我們要建立一個99乘法表的1D array,在c我們會這樣做:#include <stdio.h>;
int main(){
int i, j, ans[9*9];
for (i=1; i<=9; i++)
{
for (j=1; j<=9; j++)
{
ans[(i-1)*9+j-1] = i*j;
}
}
for (i=0; i<81; i++)
printf("%d\n", ans[i]);
return 0;
}
Python透過list comprehensions只要短短一行便解決:
ans = [a*b for b in xrange(1,10) for a in xrange(1,10)]
print ans
[註]list comprehensions中,for迴圈越後面代表越內層,即越先被作到
Filter&lambda forms
接著若我們只想要奇數的答案,便可:
filter(lambda w:w%2==1, ans)
[註]lambda 傳入參數(即function的arguments): statement