組み込み関数の活用

効率的なPythonコードの書き方

Logan Thomas

Scientific Software Technical Trainer, Enthought

Python 標準ライブラリ

  • Python 3.6 標準ライブラリ
    • すべての標準 Python インストールに含まれる
  • 組み込み型
    • list, tuple, set, dict など
  • 組み込み関数
    • print(), len(), range(), round(), enumerate(), map(), zip() など
  • 組み込みモジュール
    • os, sys, itertools, collections, math など
効率的なPythonコードの書き方

組み込み関数:range()

数値リストを直接記述する

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
効率的なPythonコードの書き方

range() を使って同じリストを作成する

# range(start,stop)
nums = range(0,11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# range(stop)
nums = range(11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
効率的なPythonコードの書き方

組み込み関数:range()

ステップ値を指定して range() を使う

even_nums = range(2, 11, 2)

even_nums_list = list(even_nums)
print(even_nums_list)
[2, 4, 6, 8, 10]
効率的なPythonコードの書き方

組み込み関数:enumerate()

インデックス付きオブジェクトリストを作成する

letters = ['a', 'b', 'c', 'd' ]

indexed_letters = enumerate(letters)

indexed_letters_list = list(indexed_letters)
print(indexed_letters_list)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
効率的なPythonコードの書き方

組み込み関数:enumerate()

開始値を指定できる

letters = ['a', 'b', 'c', 'd' ]

indexed_letters2 = enumerate(letters, start=5)

indexed_letters2_list = list(indexed_letters2)
print(indexed_letters2_list)
[(5, 'a'), (6, 'b'), (7, 'c'), (8, 'd')]
効率的なPythonコードの書き方

組み込み関数:map()

オブジェクトに関数を適用する

nums = [1.5, 2.3, 3.4, 4.6, 5.0]

rnd_nums = map(round, nums)

print(list(rnd_nums))
[2, 2, 3, 5, 5]
効率的なPythonコードの書き方

組み込み関数:map()

map()lambda(無名関数)の組み合わせ

nums = [1, 2, 3, 4, 5]

sqrd_nums = map(lambda x: x ** 2, nums)

print(list(sqrd_nums))
[1, 4, 9, 16, 25]
効率的なPythonコードの書き方

組み込み関数を使ってみましょう!

効率的なPythonコードの書き方

Preparing Video For Download...