gpt4 book ai didi

Python——对列表中的当前元素和下一个元素做些什么?

转载 作者:行者123 更新时间:2023-11-28 19:33:22 24 4
gpt4 key购买 nike

我想在列表中的当前元素和下一个元素上执行一个函数,比方说打印。当您到达列表中的最后一个元素时,您如何做到这一点而不会出现错误?

some_list = ["one", "two", "three"]

期望的输出:

curr_item: "one"
next_item: "two"

curr_item: "two"
next_item: "three"

curr_item: "three"
next_item: "end"

我尝试过的:

index = 0
for item in list_name[:-1]:
print item, list_name[index+1]
index = index+1

最佳答案

您可以压缩列表:

some_list = ["one", "two", "three"]

for cur, nxt in zip (some_list, some_list [1:] ):
print (cur, nxt)

或者如果你想要 end 值:

for cur, nxt in zip (some_list, some_list [1:] + ['end'] ):
print (cur, nxt)

关于Python——对列表中的当前元素和下一个元素做些什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22768060/

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