我需要对列表中的最后一个元素执行一些特殊的操作。有没有比这更好的方法了?
数组= [1,2,3,4,5] 对于我来说,枚举(数组)中的val: 如果(i + 1)== len(array): //最后一个元素的处理 其他: //处理其他元素
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)