next関数はイテレータの要素を順番に取得する時に使うと思っていましたが、条件に一致する最初の要素そのものを取得したい時にも使えるんだなぁと
next関数の基本
# イテレータを用意
numbers = iter([1, 2, 3, 4])
# nextで順番に要素を取り出す
print(next(numbers)) # 出力: 1
print(next(numbers)) # 出力: 2
「要素そのものを取り出す」という使い方
リストから条件に一致する最初の要素を取得する
students = [
{'id': 1, 'sex': 'male', 'rank': 1},
{'id': 2, 'sex': 'male', 'rank': 2},
{'id': 3, 'sex': 'female', 'rank': 3},
{'id': 4, 'sex': 'male', 'rank': 4},
]
# 条件に一致する要素を取得
result = next(
(item for item in students if item['sex'] ='male' and item['rank'] >= 2),None)
print(result)
# 出力: {'id': 2, 'sex': male, 'rank': 2}
next関数を使わない場合のコード
result = None
for item in students:
if item['sex'] ='male' and item['rank'] >= 2:
result = item # next関数を使えばこの部分がいらない
break
next関数を使用すると簡潔に書けるから良さそう