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のoperatorモジュール

Posted at

はじめに

LangChainとLangGraphによるRAG・AIエージェント[実践]入門
を読んでいて、10章で躓いたので、初心に戻って、一つずつ紐解いて学習することにしました。

独り言

2024年12月19日時点で約半額ポイント還元セールしていますね。
購買予約していて販売日(2日遅れ)で配信されたものの、1ヶ月待ってれば良かった。
・・・と思う反面、技術本って鮮度が大事だし、特にlangchainはバージョンアップの速度が激しいから、必要な本は、いつあるか分からないセール期間を待ってもいられないのですよね。
まぁ、この本を読んだお陰で、ネット上の知識も有意義に出来るし、多少のバージョン変更に対して読み替えも出来るようになったから、発売日に購入した後悔はないですが。
ネットで最新情報は手に入るけれど、体系的に説明してもらわないと理解できない身としては、技術書は非常に重宝しています。

サンプルコード

sample.py
import operator

# operatorモジュールの基本的な使用例
numbers = [1, 2, 3, 4, 5]
result = operator.add(10, 5)
print(f"10 + 5 = {result}")

total = sum(numbers)
print(f"合計: {total}")

product = operator.mul(3, 4)
print(f"3 * 4 = {product}")

is_greater = operator.gt(10, 5)
print(f"10 > 5: {is_greater}")```

解説

operatorモジュールは、Python の標準ライブラリの一部で、効率的な算術演算や比較演算を行うための関数を提供する。

  1. operator.add(a, b): 2つの引数の和を返す。
    例では10と5を加算している。

  2. sum(iterable): イテラブル(リストなど)の要素の合計を計算する。
    これは直接operatorモジュールの関数ではないが、内部的にoperator.addを使用している。

sum_function.py
# reduce 関数は、イテラブル(リストやタプルなど)の要素に対して、指定された関数を累積的に適用し、単一の値に集約するために使用される。
# 
# reduce(function, iterable, initializer=None)

# function は2つの引数を取る関数で、イテラブルの要素に繰り返し適用される。
# iterable は処理対象のシーケンス(リスト、タプルなど)。

import operator
from functools import reduce

numbers = [1, 2, 3, 4, 5]
total = reduce(operator.add, numbers)
print(total)
  1. operator.mul(a, b): 2つの引数の積を返す。
    例では3と4を乗算している。

  2. operator.gt(a, b): aがbより大きい場合にTrueを返す。
    例では10が5より大きいかを確認している。

operatorモジュールは、特に関数型プログラミングやリスト操作において便利である。
また、lambda関数の代わりに使用することで、コードの可読性と効率を向上させることができる。

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?