囫圇吞棗 - Python 高級編程

前言:

這絕對不是教學文章,如果您誤入此地,建議您別浪費時間;我已經事先告訴您了!

環境:

Python 2.6.4 (r264:75706, Nov 30 2009, 11:30:42)
[GCC 4.2.1 20070719  [FreeBSD]] on freebsd8
Type "help", "copyright", "credits" or "license" for more information.
>>>

語法最佳實踐

找出小於 10 的偶數整數:

>>> [i for i in range(10) if i % 2 == 0]
[0, 2, 4, 6, 8]
>>>

再來看個例子:

>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     seq[i] = '%d: %s' % (i, seq[i])
...
>>> seq
['0: one', '1: two', '2: three']

可以改寫成這樣:

>>> def _treatment(pos, element):
...     return '%d: %s' % (pos, element)
...
>>> seq = ['one', 'two', 'three']
>>> [_treatment(i, el) for i, el in enumerate(seq)]
['0: one', '1: two', '2: three']
>>>

待續...