【问题标题】:For loop accessing two iteration positions in an arrayFor循环访问数组中的两个迭代位置
【发布时间】:2016-07-01 16:26:34
【问题描述】:

我有以下代码:

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

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

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

【问题讨论】:

    标签: python arrays loops for-loop


    【解决方案1】:
    for x, y in zip(someList, someList[1:]):
        print x, y
    

    标准技术。

    【讨论】:

      【解决方案2】:

      您可以创建两个迭代器,在第二个上调用 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)
      

      【讨论】:

        猜你喜欢
        • 2015-11-13
        • 2016-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-01
        • 1970-01-01
        相关资源
        最近更新 更多