Python -- 如何对当前元素和下一个元素进行操作?
我想对列表中的当前元素和下一个元素执行一个函数,比如打印。请问怎么做才能在到达列表的最后一个元素时不出错呢?
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
8 个回答
1
给你看看:
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
2
你可以使用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
2
我们可以通过列表的索引来遍历到倒数第二个元素。列表的索引可以通过计算列表的长度和使用范围函数来得到,方法如下:
for i in range(len(some_list)-1):
print some_list[i], some_list[i+1]
输出结果:
one two
two three
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
14
你可以把这个列表压缩成一个更小的形式:
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)