LoginSignup
0
0

More than 3 years have passed since last update.

【データサイエンティスト入門】Pythonの基礎♬関数と無名関数ほか

Last updated at Posted at 2020-08-10

昨夜の続きです。
【注意】
「東京大学のデータサイエンティスト育成講座」を読んで、ちょっと疑問を持ったところや有用だと感じた部分をまとめて行こうと思う。
したがって、あらすじはまんまになると思うが内容は本書とは関係ないと思って読んでいただきたい。

Chapter1-2 Pythonの基礎

1-2-5 関数

1-2-5-1 関数の基本

関数とは、以下の性質を少なくとも一つ持つ
⓪指示に従って、定められた処理をする
①一連の処理をまとめて、共通化する
②引数を渡し、返り値を取得する

簡単な関数

③書式の基本は以下の通り

何もしない関数
def do_nothing():
    pass
do_nothing()

結果
何もしない

hello worldを出力する
def hello_world():
    print('hello world')
hello_world()

結果

hello world
引数により出力が変わる
def hello_world(arg='hello_world'):
    print(arg)

hello_world('hello_world')
hello_world('good morning')

結果

hello_world
good morning
*args引数をtupleで出力する
def hello_world(*args):
    print(args)

hello_world('hello_world','good morning')

結果
関数内及び出力はtupleになる

('hello_world', 'good morning')
**kwargs引数を辞書で出力する
def hello_world(**kwargs):
    print(kwargs)

hello_world(day='hello_world',morning='good morning', evening='good evening')

結果
関数内及び出力は辞書になり、引数名は辞書のkey, 引数の値は、辞書の値になる。

{'day': 'hello_world', 'morning': 'good morning', 'evening': 'good evening'}
返り値のある関数
def calc_multi(a, b):
    return a * b

print(calc_multi(3,5))

結果

15
fibonacci
def calc_fib(n):
    if n ==1 or n== 2:
        return 1
    else:
        return calc_fib(n-1) + calc_fib(n-2)

for n in range(1,21):
    print(calc_fib(n),end=' ')

結果

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
1-2-5-2 無名関数lambdaとmap関数

以下のように、関数名の無い関数を無名関数lambdaという。

print((lambda a, b:a*b)(3, 5))

結果

15
map関数
def calc_double(x):
    return x * 2

for num in [1, 2, 3, 4]:
    print(calc_double(num))

結果

2
4
6
8

map関数で[1, 2, 3, 4]を一度に計算して、listで出力

print(list(map(calc_double, [1, 2, 3, 4])))

結果

[2, 4, 6, 8]
map関数とlambda

通常の関数をlambdaに置き換えて、一行で出力できる

print(list(map(lambda x : x*2, [1, 2, 3, 4])))

結果

[2, 4, 6, 8]
練習問題1-2
print((lambda x : sum(x))(i for i in range(1,51)))
print((lambda x : sum(x))(range(1,51)))
print( sum(i for i in range(1,51)))
print( sum(range(1,51)))
print(reduce(lambda x, y: x + y, range(1,51)))

結果

1275
filter関数とreduce関数
a = [-1, 3, -5, 7, -9]
print(list(filter(lambda x: abs(x) > 5, a)))

結果

[7, -9]

reduce関数は要素の逐次加算した結果

from functools import reduce
print(reduce(lambda x, y: x + y, a))

結果

-5

【参考】
Python の基本的な高階関数( map() filter() reduce() )

まとめ

・関数の基本
*args**kwargsの使い方
・無名関数lambda, map関数, filter関数, そしてreduce関数の使い方を並べてみた

基本に立ち返って、並べてみると分かり易い。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0