用于循环访问数组中的两个迭代位置

时间:2016-07-01 16:26:34

标签: python arrays loops for-loop

我有以下代码:

someList = ['a', 'b', 'c', 'd', 'e', 'f']

for i,j in enumerate(someList) step 2:
    print('%s, %s' % (someList[i], someList[i+1]))

我的问题是,有没有办法简化数组上的迭代,以避免enumerate部分并且仍然一次访问两个变量?

2 个答案:

答案 0 :(得分:5)

for x, y in zip(someList, someList[1:]):
    print x, y

标准技术。

答案 1 :(得分:1)

你可以创建两个迭代器,在第二个上调用next,然后压缩zip,这样就不需要通过切片来复制列表元素了:

someList = ['a', 'b', 'c', 'd', 'e', 'f']

it1, it2 = iter(someList),  iter(someList)
next(it2)

for a,b in zip(it1,  it2):
   print(a, b)