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:45

A simple solution.

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

for i in range(0, len(l), 2):
    print str(l[i]), '+', str(l[i + 1]), '=', str(l[i] + l[i + 1])
查看更多
孤独总比滥情好
3楼-- · 2018-12-31 04:45

Closest to the code you wrote:

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

for i,k in zip(l[::2], l[1::2]):
    print(str(i), '+', str(k), '=', str(i+k))

Output:

1+2=3
3+4=7
5+6=11
查看更多
美炸的是我
4楼-- · 2018-12-31 04:49

I need to divide a list by a number and fixed like this.

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

def divideByN(data, n):
        return [data[i*n : (i+1)*n] for i in range(len(data)//n)]  

>>> print(divideByN(l,2))
[[1, 2], [3, 4], [5, 6]]

>>> print(divideByN(l,3))
[[1, 2, 3], [4, 5, 6]]
查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 04:52

Use the zip and iter commands together:

zip(*[iter(l)]*2)

which I found in the Python 3 zip documentation:

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

for i,j in zip(*[iter(l)]*2):
    print("{}+{}={}".format(str(i),str(j),str(i+j)))

Which results in:

1+2=3
3+4=7
5+6=11
查看更多
像晚风撩人
6楼-- · 2018-12-31 04:53

You need a pairwise() (or grouped()) implementation.

For Python 2:

from itertools import izip

def pairwise(iterable):
    "s -> (s0, s1), (s2, s3), (s4, s5), ..."
    a = iter(iterable)
    return izip(a, a)

for x, y in pairwise(l):
   print "%d + %d = %d" % (x, y, x + y)

Or, more generally:

from itertools import izip

def grouped(iterable, n):
    "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
    return izip(*[iter(iterable)]*n)

for x, y in grouped(l, 2):
   print "%d + %d = %d" % (x, y, x + y)

In Python 3, you can replace izip with the built-in zip() function, and drop the import.

All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.

N.B: This should not be confused with the pairwise recipe in Python's own itertools documentation, which yields s -> (s0, s1), (s1, s2), (s2, s3), ..., as pointed out by @lazyr in the comments.

查看更多
初与友歌
7楼-- · 2018-12-31 04:55

We can also just make the list a set of tuples

l = [(1,2),(3,4)]
l.append((5,6))
for r,c in l:
   print r,c

output:

1 2
3 4
5 6
查看更多
登录 后发表回答