我想在列表中的当前和下一个元素上执行一个函数,比如print。当你到达列表中的最后一个元素时,如何在不收到错误的情况下执行此操作?
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
答案 0 :(得分:9)
您可以压缩列表:
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)
答案 1 :(得分:4)
您可以使用itertools.izip_longest
:
>>> from itertools import izip_longest
>>> some_list = ["one", "two", "three"]
>>> for x, y in izip_longest(some_list, some_list[1:], fillvalue='end'):
print 'cur_item', x
print 'next_item', y
cur_item one
next_item two
cur_item two
next_item three
cur_item three
next_item end
答案 2 :(得分:1)
我们可以使用列表索引迭代到倒数第二个元素。可以使用len和range函数计算列表索引,如下所示:
for i in range(len(some_list)-1):
print some_list[i], some_list[i+1]
输出:
one two
two three
答案 3 :(得分:1)
您可以使用itertools
中的成对配方,例如:
from itertools import izip_longest, tee
def pairwise(iterable):
fst, snd = tee(iterable)
next(snd, None)
return izip_longest(fst, snd, fillvalue='end')
for fst, snd in pairwise(['one', 'two', 'three']):
print fst, snd
#one two
#two three
#three end
答案 4 :(得分:1)
单线解决方案
[(cur, nxt) for cur, nxt in zip(some_list, some_list[1:])]
答案 5 :(得分:0)
您可以尝试以下内容:
for i in range(len(some_list)):
print("curr_item: " + some_list[i])
if i < len(some_list)-1:
print("next_item: " + some_list[i+1])
else:
print('next_item: "end"')
答案 6 :(得分:0)
您要去的地方
some_list = ["one", "two", "three"]
for f, r in enumerate(some_list):
try:
print('curr_item : ',some_list[f])
print('next_item : ',some_list[f+1])
print()
except IndexError :
pass
输出:
curr_item : one
next_item : two
curr_item : two
next_item : three
curr_item : three
答案 7 :(得分:0)
使用链表来评估列表
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
self.previousval=None
class LinkedList:
def __init__(self):
self.headval = None
def listprint(self):
node = self.headval
while node is not None:
if node.previousval!=None:
print("Previous Node",node.previousval.dataval)
else:
print("Previous Node is None")
print("CurrentNode", node.dataval)
print("\n")
node = node.nextval
list1 = LinkedList()
some_list = ["one", "two", "three"]
for item in some_list:
if list1.headval==None:
currentNode=Node(item)
list1.headval = currentNode
currentNode.previousval=None
previousNode=currentNode
else:
currentNode=Node(item)
currentNode.previousval=previousNode
previousNode.nextval=currentNode
previousNode=currentNode
list1.listprint()
输出:
Previous Node is None
CurrentNode one
Previous Node one
CurrentNode two
Previous Node two
CurrentNode three