Pythonの対話型インタプリタが便利だという話を5分で

http://www.python.org/download/
Pythonは上からダウンロードして適当にインストールする感じで。
で、今回は[12,24,36,48,60]など数字の組み合わせが与えられた場合に、
それぞれの要素が各要素の総和に占める割合を出してみる。
1つずつ計算するのは面倒だけどプログラム書くほどでも無いよねっていう。

とりあえずコマンドラインから対話型インタプリタを起動。

> python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

とりあえず扱う数字の集合をリストに入れる。

>>> l = [12,24,36,48,60]
>>> l # 確認
[12, 24, 36, 48, 60]
>>>

とりあえず総和を求めたいけどsum関数的なものは・・・

>>> s = sum(l) # あったー!
>>> s # 確認
180
>>>

後は各要素を総和で割れば良し。とりあえずmap関数ぐらいあるだろ。

>>> help(map) # helpで使い方を確認
Help on built-in function map in module __builtin__:

map(...)
    map(function, sequence[, sequence, ...]) -> list

    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list o
    the items of the sequence (or a list of tuples if more than one sequence)

>>>

無名関数で各要素を総和で割らせればいいか

>>> map((lambda x : x / s), l)
[0, 0, 0, 0, 0] # っておーい!
>>>

整数で整数を割ってた。分母をfloatにしておく。

>>> map((lambda x : x / float(s)), l)
[0.066666666666666666, 0.13333333333333333, 0.20000000000000001, 0.26666666666666666, 0.33333333333333331]
>>>

完成。リスト内包表記を使う場合は以下の感じで。

>>> [ x / 180.0 for x in l] # 各要素がx/180.0となるリストを作る。ただしxはlの各要素
[0.066666666666666666, 0.13333333333333333, 0.20000000000000001, 0.26666666666666666, 0.33333333333333331]
>>>

Pythonあんまり関係無かったか。とりあえずhelpが便利という話。
もしこれからPythonを使おうって人がいた場合、
公式のチュートリアル*1が充実してるからそっちを読めば使えるようになると思うけど、
自分が読んだ入門書の中からあえて1冊選ぶとしたら、みんなのPython (Amazon)辺りがお薦め。

*1:"Python チュートリアル"辺りでググれば出る