0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「順番で取り出す」だけじゃないnext関数

Posted at

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関数を使用すると簡潔に書けるから良さそう

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?