Collect every pair of elements from a list into tuples in Python [duplicate]
I have a list of small integers, say:
[1, 2, 3, 4, 5, 6]
I wish to collect the sequential pairs and return a new list containing tuples created from those pairs, i.e.:
[(1, 2), (3, 4), (5, 6)]
I know there must be a really simple way to do this, but can't quite work it out.
Th开发者_运维问答anks
Well there is one very easy, but somewhat fragile way, zip it with sliced versions of itself.
zipped = zip(mylist[0::2], mylist[1::2])
In case you didn't know, the last slice parameter is the "step". So we select every second item in the list starting from zero (1, 3, 5). Then we do the same but starting from one (2, 4, 6) and make tuples out of them with zip
.
Apart from the above answers, you also need to know the simplest of way too (if you hadn't known already)
l = [1, 2, 3, 4, 5, 6]
o = [(l[i],l[i+1]) for i in range(0,len(l),2)]
Straight from the Python documentation of the itertools module:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
l = [1, 2, 3, 4, 5, 6]
for pair in pairwise(l):
print pair
精彩评论