如何检查项是否是python中迭代的最后一项

Jeo*_*eon 4 python iteration

例如,我有一个字符串列表:

str_list =['one', 'two', 'three', 'four', 'five']
Run Code Online (Sandbox Code Playgroud)

我想在屏幕上打印所有这些:

for c in str_list:
    print c
    print ', ' # word separator
Run Code Online (Sandbox Code Playgroud)

这导致:

one, two, three, four, five,
Run Code Online (Sandbox Code Playgroud)

这里,行末不需要逗号,我不想打印它.如何修改上面的代码而不是打印最后一个逗号?

它可以通过以下方式解决enumerate:

for idx, c in enumerate(str_list):
    print c
    if idx < len(str_list) - 1:
        print ','
Run Code Online (Sandbox Code Playgroud)

但是,我认为可能有更优雅的方式来处理这个问题.

编辑:也许我以为我举了一个太简单的例子.假设我应该为每个迭代调用函数x(),除了最后一个迭代:

for idx, x in enumerate(list_x):
    if idx < len(list_x) - 1:
        something_right(x)
    else:
        something_wrong(x)
Run Code Online (Sandbox Code Playgroud)

vau*_*tah 6

里面', '.join(['one', 'two', 'three', 'four', 'five'])有某种迭代;)

这实际上是最优雅的方式.

这是另一个:

# Everything except the last element
for x in a[:-1]:
    print(x + ', ', end='')

# And the last element
print(a[-1])
Run Code Online (Sandbox Code Playgroud)

输出 one, two, three, four, five


tde*_*ney 4

一个问题if idx < len(list_x) - 1:是它只适用于序列,而不适用于任何迭代器。您可以编写自己的生成器,它会向前看并告诉您是否已到达终点。

def tag_last(iterable):
    """Given some iterable, returns (last, item), where last is only
    true if you are on the final iteration.
    """
    iterator = iter(iterable)
    gotone = False
    try:
        lookback = next(iterator)
        gotone = True
        while True:
            cur = next(iterator)
            yield False, lookback
            lookback = cur
    except StopIteration:
        if gotone:
            yield True, lookback
        raise StopIteration()
Run Code Online (Sandbox Code Playgroud)

在 python 2 中它看起来像:

>>> for last, i in tag_last(xrange(4)):
...     print(last, i)
... 
(False, 0)
(False, 1)
(False, 2)
(True, 3)
>>> for last, i in tag_last(xrange(1)):
...     print(last, i)
... 
(True, 0)
>>> for last, i in tag_last(xrange(0)):
...     print(last, i)
... 
>>> 
Run Code Online (Sandbox Code Playgroud)