【Python】 Python ~ 基本編 / ラムダ lambda ~

■ はじめに

ラムダ lambda を勉強する

目次

【1】lambda
 1)構文
 2)サンプル
【2】filter
 1)応用:空要素を除外
【3】groupby
【4】map

【1】lambda

* 短い関数を簡潔に定義できる

1)構文

lambda 【引数】: 【返り値】

関数にすると...

def sample_function(【引数】):
    return 【返り値】

2)サンプル

例1:簡単な例

sum = lambda x, y: x + y

# 以下と同じ
#def sum(x, y):
#   return x + y

sum(2,3)

https://qiita.com/nagataaaas/items/531b1fc5ce42a791c7df

例2:処理を切り替える

list = ["mon", "tue", "wed", "Thu", "Fri", "SAT", "Sun"]

def to_something(words, func):
  for word in words:
    print(func(word))

to_something(list, lambda word: word.capitalize())
print("********")
to_something(list, lambda word: word.upper())
print("********")
to_something(list, lambda word: word.lower())
print("********")

【2】filter

* 以下の関連記事を参照のこと

https://dk521123.hatenablog.com/entry/2022/02/14/000000
例1

target = "SELECT * FROM hello WHERE id='1'"
demo_set = {"world", "hello", "!!!"}
result = list(filter(lambda x: x in target, demo_set))
print(result) # ['hello']

target = "SELECT * FROM hello WHERE id='1'"
demo_set = {"world", "dummy", "!!!"}
result = list(filter(lambda x: x in target, demo_set))
print(result) # []

例2:dict of list

# やりたいこと:"user-task-accumulators"の値のデータセットを分割する
targets = {
  "job-accumulators":[],
  "user-task-accumulators": [ {
    "name": "avglen",
    "type": "DoubleCounter",
    "value": "61.5162972"
  },
  {
    "name": "rows_count",
    "type": "IntCounter",
    "value": "1"
  } ],
  "serialized-user-task-accumulators":[]
}
task_accumulators = targets["user-task-accumulators"]

row_count = list(filter(lambda x: "count" in x["name"] , task_accumulators))
others = list(filter(lambda x: "count" not in x["name"] , task_accumulators))

# row_count = [{'name': 'rows_count', 'type': 'IntCounter', 'value': '1'}]
print(f"row_count = {row_count}")
# others = [{'name': 'avglen', 'type': 'DoubleCounter', 'value': '61.5162972'}]
print(f"others = {others}")

1)応用:空要素を除外

* 空要素を除外として、 filter / lambda を使う。

https://1-notes.com/python-remove-empty-values-from-list/
https://qiita.com/github-nakasho/items/a08e21e80cbc9761db2f
サンプル

demo_list = ["Hello", "", "World", "", "!!!", ""]

results = list(filter(lambda x: x != "", demo_list))
print(results)
# ['Hello', 'World', '!!!']

【3】groupby

* SQL の Group by のように重複排除に役立つ。

【4】map

* 以下の関連記事にまとめた。

Python ~ 基本編 / map ~
https://dk521123.hatenablog.com/entry/2021/03/29/000000

関連記事

Python ~ 基本編 / map ~
https://dk521123.hatenablog.com/entry/2021/03/29/000000
Python ~ 基本編 / リスト・タプル・辞書・集合 ~ https://dk521123.hatenablog.com/entry/2019/10/12/084943
Python ~ namedtuple / 簡易クラス ~
https://dk521123.hatenablog.com/entry/2020/11/10/134233
Python ~ 基本編 / 制御文 ~
https://dk521123.hatenablog.com/entry/2019/08/25/000330
PythonJSONあれこれ ~
https://dk521123.hatenablog.com/entry/2022/02/14/000000
Python ~ ウォルラス演算子 (:=) ~
https://dk521123.hatenablog.com/entry/2024/07/18/002712