Iterating over every two elements in a list

2018-12-31 04:18发布

How do I make a for loop or a list comprehension so that every iteration gives me two elements?

l = [1,2,3,4,5,6]

for i,k in ???:
    print str(i), '+', str(k), '=', str(i+k)

Output:

1+2=3
3+4=7
5+6=11

标签: python list
19条回答
闭嘴吧你
2楼-- · 2018-12-31 04:55

Using typing so you can verify data using mypy static analysis tool:

from typing import Iterator, Any, Iterable, TypeVar, Tuple

T_ = TypeVar('T_')
Pairs_Iter = Iterator[Tuple[T_, T_]]

def legs(iterable: Iterator[T_]) -> Pairs_Iter:
    begin = next(iterable)
    for end in iterable:
        yield begin, end
        begin = end
查看更多
有味是清欢
3楼-- · 2018-12-31 04:56

Here we can have alt_elem method which can fit in your for loop.

def alt_elem(list, index=2):
    for i, elem in enumerate(list, start=1):
        if not i % index:
           yield tuple(list[i-index:i])


a = range(10)
for index in [2, 3, 4]:
    print("With index: {0}".format(index))
    for i in alt_elem(a, index):
       print(i)

Output:

With index: 2
(0, 1)
(2, 3)
(4, 5)
(6, 7)
(8, 9)
With index: 3
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
With index: 4
(0, 1, 2, 3)
(4, 5, 6, 7)

Note: Above solution might not be efficient considering operations performed in func.

查看更多
忆尘夕之涩
4楼-- · 2018-12-31 04:59

While all the answers using zip are correct, I find that implementing the functionality yourself leads to more readable code:

def pairwise(it):
    it = iter(it)
    while True:
        yield next(it), next(it)

The it = iter(it) part ensures that it is actually an iterator, not just an iterable. If it already is an iterator, this line is a no-op.

Usage:

for a, b in pairwise([0, 1, 2, 3, 4, 5]):
    print(a + b)
查看更多
美炸的是我
5楼-- · 2018-12-31 04:59

Apologies for being late.I hope this will be even more elegant way of doing it.

a = [1,2,3,4,5,6]
zip(a[::2], a[1::2])

[(1, 2), (3, 4), (5, 6)]
查看更多
临风纵饮
6楼-- · 2018-12-31 05:00

The title of this question is misleading, you seem to be looking for consecutive pairs, but if you want to iterate over the set of all possible pairs than this will work :

for i,v in enumerate(items[:-1]):
        for u in items[i+1:]:
查看更多
还给你的自由
7楼-- · 2018-12-31 05:01
>>> l = [1,2,3,4,5,6]

>>> zip(l,l[1:])
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

>>> zip(l,l[1:])[::2]
[(1, 2), (3, 4), (5, 6)]

>>> [a+b for a,b in zip(l,l[1:])[::2]]
[3, 7, 11]

>>> ["%d + %d = %d" % (a,b,a+b) for a,b in zip(l,l[1:])[::2]]
['1 + 2 = 3', '3 + 4 = 7', '5 + 6 = 11']
查看更多
登录 后发表回答