gpt4 book ai didi

python - 如何在 Python 中以不同方式处理列表中的最后一个元素?

转载 作者:IT老高 更新时间:2023-10-28 20:32:48 26 4
gpt4 key购买 nike

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

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)

关于python - 如何在 Python 中以不同方式处理列表中的最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com