简体   繁体   English

迭代列表中的每两个元素以执行列表 python

[英]iterate every two elements in the list to do something of the list python

I have a list named newList and inside the list there is another list of information with JSON code.我有一个名为newList的列表,列表中还有另一个带有 JSON 代码的信息列表。 I want to iterate every two elements in the newList to do something for those two elements.我想迭代newList中的每两个元素来为这两个元素做一些事情。

ex: if my newList length is 8, I want to able do a for loop or access the 0 and 1 element, do something with the information inside those two elements, then go to 1 and 2 elements and do something with those elements.例如:如果我的newList长度为 8,我希望能够执行 for 循环或访问01元素,对这两个元素内的信息执行某些操作,然后转到12元素并对这些元素执行某些操作。

My code:我的代码:

data = np.arange(len(newList))
 def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

  for v, w in pairwise(data):
    print(v, w)

print result:打印结果:

0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
12 13
13 14
14 15

What I am looking for:我在找什么:

0 1
2 3
4 5
6 7
8 9
10 11
12 13
14 15 

You can create a single iterator and then zip it with itself:您可以创建一个迭代器,然后将其与自身一起压缩:

def pairwise(iterable):
    return zip(*[iter(iterable)]*2)

which is similar to:这类似于:

def pairwise(iterable):
    i = iter(iterable)
    return zip(i, i)

Do you want (0, 1), (1, 2) or (0, 1), (2, 3)?你想要 (0, 1), (1, 2) 还是 (0, 1), (2, 3)? Your question seems to say you want one, and it seems to say you want the other.你的问题似乎说你想要一个,它似乎说你想要另一个。

Anyway, here's some code for the latter:无论如何,这是后者的一些代码:

#!/usr/local/cpython-3.8/bin/python3


import itertools


def test_data(n):
    # Yes, there's a simpler way of doing this.
    for i in range(n):
        yield i


def two_up(iterable):
    left_iterable, right_iterable = itertools.tee(iterable)
    left_every_other = itertools.islice(left_iterable, 0, None, 2)
    right_every_other = itertools.islice(right_iterable, 1, None, 2)
    for tuple_ in zip(left_every_other, right_every_other):
        yield tuple_


def main():
    it = test_data(10)
    for thing in two_up(it):
        print(thing)


main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM