当使用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

我如何简化或改进它?


当前回答

如果你只是想修改data_list中的最后一个元素,那么你可以简单地使用符号:

L[-1]

然而,看起来你做的还不止这些。你的方式并没有什么问题。我甚至快速浏览了一些Django的模板标签代码,它们做的基本和你做的一样。

其他回答

谷歌让我想到了这个老问题,我想我可以用不同的方法来解决这个问题。

这里的大多数答案将处理一个正确的处理for循环控件,但如果data_list是可销毁的,我建议你从列表中弹出项目,直到你得到一个空列表:

while True:
    element = element_list.pop(0)
    do_this_for_all_elements()
    if not element:
        do_this_only_for_last_element()
        break
    do_this_for_all_elements_but_last()

如果不需要对最后一个元素做任何操作,甚至可以使用while len(element_list)。我发现这个解决方案比处理next()更优雅。

如果要循环List, 使用枚举函数是最好的尝试之一。

for index, element in enumerate(ListObj):
    # print(index, ListObj[index], len(ListObj) )

    if (index != len(ListObj)-1 ):
        # Do things to the element which is not the last one
    else:
        # Do things to the element which is the last one

你的方法没有错,除非你有10万个循环,想要保存10万个“if”语句。在这种情况下,你可以这样做:

iterable = [1,2,3] # Your date
iterator = iter(iterable) # get the data iterator

try :   # wrap all in a try / except
    while 1 : 
        item = iterator.next() 
        print item # put the "for loop" code here
except StopIteration, e : # make the process on the last element here
    print item

输出:

1
2
3
3

但说真的,在你的情况下,我觉得这太过分了。

在任何情况下,你可能会更幸运的切片:

for item in iterable[:-1] :
    print item
print "last :", iterable[-1]

#outputs
1
2
last : 3

或者只是:

for item in iterable :
    print item
print iterable[-1]

#outputs
1
2
3
last : 3

最终,一个KISS的方式来做你的事情,这将适用于任何迭代对象,包括那些没有__len__的迭代对象:

item = ''
for item in iterable :
    print item
print item

Ouputs:

1
2
3
3

如果我这样做的话,对我来说很简单。

我只是遇到了这个问题,我的通用解决方案使用迭代器:

from typing import TypeVar, Iterable
E = TypeVar('E')

def metait(i: Iterable[E]) -> Iterable[tuple[E, bool, bool]]:

    first = True
    previous = None
    for elem in i:
        if previous:
            yield previous, first, False
            first = False
        previous = elem

    if previous:
        yield previous, first, True

您将收到一个元组,其中包含第一项和最后一项的原始元素和标志。它可以用于每个可迭代对象:

d = {'a': (1,2,3), 'b': (4,5,6), 'c': (7,8,9)}

for (k,v), is_first, is_last in metait(d.items()):
    print(f'{k}: {v}  {is_first} {is_last}')

这将给你:

a: (1, 2, 3)  True False
b: (4, 5, 6)  False False
c: (7, 8, 9)  False True

我想到的一个简单的解决办法是:

for i in MyList:
    # Check if 'i' is the last element in the list
    if i == MyList[-1]:
        # Do something different for the last
    else:
        # Do something for all other elements

第二个同样简单的解决方法是使用计数器:

# Count the no. of elements in the list
ListLength = len(MyList)
# Initialize a counter
count = 0

for i in MyList:
    # increment counter
    count += 1
    # Check if 'i' is the last element in the list
    # by using the counter
    if count == ListLength:
        # Do something different for the last
    else:
        # Do something for all other elements