Python.use(better)《余録》組み込み関数 map
‖記事一覧‖ Python.use(better)《Python3.1》
《余録》組み込み関数 map
《著》小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28
さまざまな事例
簡単な事例を使って、組み込み関数 map の理解を深めます。
《Note》Smalltalk-80 セミナー用に作成した課題を、Python で再構成しました。この課題では「コレクションを扱う基本的なプロトコル(collect:/select:/reject:/detect:/inject:into:)を利用する」という制約を課してあるので、問題解決のための「最適解」を示すものではありません。
組み込み関数 map
$ python3.1 Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> print(map.__doc__) map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted. >>>
関数 func を、iterables の各要素に適用した結果を列挙する、イテレーターを生成します。
■ 事例:リストの内包
>>> [ord(e) for e in "ABC"] [65, 66, 67]
関数 ord を、文字列 "ABC" の各要素 e(長さ1の文字列)に適用した結果を列挙した、リストが得られます。リストの内包と同等の結果は、次のように、組み込み関数 map でも得られます。
>>> map(ord, "ABC")
<map object at 0xe7a90>
>>> list(_)
[65, 66, 67]
関数 ord を、文字列 "ABC" の各要素 e に適用した結果を列挙する、イテレーターが得られます。そこで、これをもとにリスト list を生成します。
■ 事例:ラムダ式
>>> [e.lower() for e in "ABC"] ['a', 'b', 'c']
メソッド lower を、文字列 "ABC" の各要素 e(長さ1の文字列)に適用した結果を列挙した、リストが得られます。リストの内包と同等の結果は、次のように、組み込み関数 map でも得られます。
>>> map(lambda e:e.lower(), "ABC")
<map object at 0xe7d50>
>>> list(_)
['a', 'b', 'c']
メソッド lower を、文字列 "ABC" の各要素 e に適用した結果を列挙する、イテレーターが得られます。そこで、これをもとにリスト list を生成します。
》こちらに移動中です《
↑TOP
関連記事
- Python への扉
- INDEX《Python》map
- 2002-01-26 Python.use(better)《余録》comprehension: list
Last updated♪2009/11/03