如何在Python中不同地处理列表中的最后一个元素?

我需要对列表中的最后一个元素做一些特殊的操作。
有什么比这更好的方法吗?

array = [1,2,3,4,5] 
for i, val in enumerate(array): 
  if (i+1) == len(array): 
    // Process for the last element 
  else: 
    // Process for the other element 
for item in list[:-1]:
    print "Not last: ", item
print "Last: ", list[-1]

如果你不想复制列表,你可以做一个简单的生成器:

# itr is short for "iterable" and can be any sequence, iterator, or generator

def notlast(itr):
    itr = iter(itr)  # ensure we have an iterator
    prev = itr.next()
    for item in itr:
        yield prev
        prev = item

# lst is short for "list" and does not shadow the built-in list()
# 'L' is also commonly used for a random list name
lst = range(4)
for x in notlast(lst):
    print "Not last: ", x
print "Last: ", lst[-1]

notlast的另一个定义:

import itertools
notlast = lambda lst:itertools.islice(lst, 0, len(lst)-1)
http://stackoverflow.com/questions/2429098/how-to-treat-the-last-element-in-list-differently-in-python

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何在Python中不同地处理列表中的最后一个元素?