Python で「for」ループの最後の要素を検出する方法は何ですか? 質問する

Python で「for」ループの最後の要素を検出する方法は何ですか? 質問する

ループで反復処理するときに、入力の最後の要素を特別に扱うにはどうすればよいですかfor? 特に、最後の要素の「後」ではなく「間」でのみ発生するコードがある場合、コードをどのように構成すればよいですか?

現在、私は次のようなコードを書いています:

for i, data in enumerate(data_list):
    code_that_is_done_for_every_element
    if i != len(data_list) - 1:
        code_that_is_done_between_elements

これを簡素化または改善するにはどうすればよいでしょうか?

ベストアンサー1

ほとんどの場合、最後の反復ではなく最初の反復を特別なケースにする方が簡単 (かつ安価) です。

first = True
for data in data_list:
    if first:
        first = False
    else:
        between_items()

    item()

これは、 を持たない反復可能オブジェクトでも機能しますlen()

file = open('/path/to/file')
for line in file:
    process_line(line)

    # No way of telling if this is the last line!

それ以外では、何をしようとしているかによって異なるため、一般的に優れた解決策があるとは思いません。たとえば、リストから文字列を作成する場合、ループを使用するよりも「特別なケース」をstr.join()使用する方が当然優れています。for


同じ原理をよりコンパクトに使用します。

for i, line in enumerate(data_list):
    if i > 0:
        between_items()
    item()

見覚えがあるでしょう? :)


len()@ofko や、反復可能オブジェクトの現在の値が最後の値であるかどうかを本当に確認する必要がある他のユーザーの場合は、先を見据える必要があります。

def lookahead(iterable):
    """Pass through all values from the given iterable, augmented by the
    information if there are more values to come after the current one
    (True), or if it is the last value (False).
    """
    # Get an iterator and pull the first value.
    it = iter(iterable)
    last = next(it)
    # Run the iterator to exhaustion (starting from the second value).
    for val in it:
        # Report the *previous* value (more to come).
        yield last, True
        last = val
    # Report the last value.
    yield last, False

次のように使用できます:

>>> for i, has_more in lookahead(range(3)):
...     print(i, has_more)
0 True
1 True
2 False

おすすめ記事