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

标签 python list

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

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/

相关文章:

python - 如何使用 aggfunc 'min' 在dask中执行pivot_table?

list - Dart 列表计数在拆分空字符串时显示一个

list - 如何在 Groovy 中将列表拆分为大小相等的列表?

python - 在数据框中创建最大/最小列时选择列的问题

python - 使用 s3fs 下载文件

python - 属性错误 : can't delete attribute

python - 如何将正负十进制数列表规范化到特定范围

python - 根据值获取列表的列表索引范围

python - 在列表的列表中操作字符串

python - 在 Django 模板中替代 {% if request.user.is_active %}