0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】毎週勉強するシリーズ ~リスト関数~

Posted at

概要

AI が流行ってる昨今 Python は必須級のスキルになってきてます。
時代に取り残されないようにコツコツと Python を勉強しようと思います!
三日坊主にならないように Qita でアウトプットしながら進めます💪

今日やること

とほほのPython入門 - リスト・タプル・辞書 のリスト関数(map(), filter(), reduce())を理解する。

map()

map() はリストの各要素に対して処理を行い、行った結果を返します。
下記の例では各要素を2倍にする処理を行います。

a = [1, 2, 3]

def double(x): return x * 2

print(list(map(double, a)))                  #=> [2, 4, 6] : 関数方式
print(list(map(lambda x: x * 2, a)))         #=> [2, 4, 6] : lambda方式
print([x * 2 for x in a])                    #=> [2, 4, 6] : 内包表記(後述)

list() はリスト型に型変換するための標準関数です。
なんで変換してるのかなぁと思って調べたら、map() は mapオブジェクトを返却するようです。
JavaScript の map() みたいにリストを返却するのかなって思ってましたが、Python は違うようですね。

filter()

filter() はリストの各要素に対して処理を行い、処理結果が真となる要素のみを取り出します。
下記の例では各要素から奇数のみを取り出します。

a = [1, 2, 3]

def isodd(x): return x % 2
print(list(filter(isodd, a)))              #=> [1, 3] : 関数方式
print(list(filter(lambda x: x % 2, a)))    #=> [1, 3] : lambda方式
print([x for x in a if x % 2])             #=> [1, 3] : 内包表記(後述)

reduce()

reduce() はリストの最初の2要素を引数に処理を呼び出し、結果と次の要素を引数に処理の呼び出しを繰り返し、単一の結果を返します。
下記の例では、各要素の合計を計算しています。

from functools import reduce

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

def add(x, y): return x + y
print(reduce(add, a))                  #=> 15 : 関数方式
print(reduce(lambda x, y: x + y, a))   #=> 15 : lambda方式

感想

今日はリスト関数をやってみました!

今回も見ていただきありがとうございました。
また次回お会いしましょう!!

次回やること

とほほのPython入門 - リスト・タプル・辞書 のリストの内包表記を理解する。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?