Python检查列表的第一个和最后一个索引

Hel*_*nar 10 python list

假设我有一个包含对象的object_list列表.

我想检查我当前的迭代是在第一次还是最后一次.

for object in object_list:
    do_something
    if first_indexed_element:
        do_something_else
    if last_indexed_element:
        do_another_thing
Run Code Online (Sandbox Code Playgroud)

怎么能实现这一目标?我知道我可以使用范围和计数索引,但如果感觉笨拙.

问候

Fel*_*ing 15

你可以使用enumerate():

for i, obj in enumerate(object_list):
    do_something
    if i == 0:
        do_something_else
    if i == len(object_list) - 1:
        do_another_thing
Run Code Online (Sandbox Code Playgroud)

但是,不是在每次迭代中检查您正在处理的对象,也许这样的事情会更好:

def do_with_list(object_list):
    for obj in object_list:
        do_something(obj)
    do_something_else(object_list[0])
    do_another_thing(object_list[-1])
Run Code Online (Sandbox Code Playgroud)

想象一下,你有一个包含100个对象的列表,然后进行198次不必要的比较,因为当前元素不能是列表中的第一个或最后一个元素.

但这取决于语句是否必须以某种顺序执行以及它们正在做什么.


顺便说一句.不要影子object,它已经是Python中的标识符;)


Aut*_*tic 13

li = iter(object_list)

obj = next(li)

do_first_thing_with(obj)

while True:
    try:
        do_something_with(obj)
        obj = next(li)
    except StopIteration:
        do_final_thing_with(obj)
        break
Run Code Online (Sandbox Code Playgroud)