Pairwise circular Python 'for' loop

后端 未结 18 869
执念已碎
执念已碎 2020-12-24 10:24

Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first.

So for instance, if I have the list

18条回答
  •  萌比男神i
    2020-12-24 10:55

    I'd use a slight modification to the pairwise recipe from the itertools documentation:

    def pairwise_circle(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ... (s,s0)"
        a, b = itertools.tee(iterable)
        first_value = next(b, None)
        return itertools.zip_longest(a, b,fillvalue=first_value)
    

    This will simply keep a reference to the first value and when the second iterator is exhausted, zip_longest will fill the last place with the first value.

    (Also note that it works with iterators like generators as well as iterables like lists/tuples.)

    Note that @Barry's solution is very similar to this but a bit easier to understand in my opinion and easier to extend beyond one element.

提交回复
热议问题