How to convert int list to tuple list

I want to convert a list like this

l1 = [1,2,3,4,5,6,7,8] 

to

 l2 = [(1,2),(3,4),(5,6),(7,8)] 

because you want to execute a loop

 for x,y in l2: draw_thing(x,y) 
+4
source share
9 answers

Based on Nick D's answer:

 >>> from itertools import izip >>> t = [1,2,3,4,5,6,7,8,9,10,11,12] >>> for a, b in izip(*[iter(t)]*2): ... print a, b ... 1 2 3 4 5 6 7 8 9 10 11 12 >>> for a, b, c in izip(*[iter(t)]*3): ... print a, b, c ... 1 2 3 4 5 6 7 8 9 10 11 12 >>> for a, b, c, d in izip(*[iter(t)]*4): ... print a, b, c, d ... 1 2 3 4 5 6 7 8 9 10 11 12 >>> for a, b, c, d, e, f in izip(*[iter(t)]*6): ... print a, b, c, d, e, f ... 1 2 3 4 5 6 7 8 9 10 11 12 >>> 

Not readable, but it shows a compact way to get the right tuple size.

+7
source

One good way:

 from itertools import izip it = iter([1, 2, 3, 4]) for x, y in izip(it, it): print x, y 

Output:

 1 2 3 4 >>> 
+10
source

View using python slicing statement:

 l2 = zip(l1[0::2], l1[1::2]) 
+5
source

Take a look at the grouper function from itertools docs .

 from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) 

In your case, use it like this:

 l1 = [1,2,3,4,5,6,7,8] for (x, y) in grouper(2, l1): draw_thing(x, y) 
+2
source

You can do:

 l2 = [] for y in range(0, len(l1), 2): l2.append((l1[y], l1[y+1])) 

I do not do any checks to make sure l1 has an even number of entries, etc.

0
source

Not the most elegant solution

 l2 = [(l1[i], l1[i+1]) for i in xrange(0,len(l1),2)] 
0
source

No need to create a new list. You can simply iterate over the list in steps 2 instead of 1. I use len(L) - 1 as the top border so you don't try to access the end of the list.

 for i in range(0, len(L) - 1, 2): draw_thing(L[i], L[i + 1]) 
0
source
  list = [1,2,3,4,5,6] it = iter(list) newlist = [(x, y) for x, y in zip(it, it)] 
0
source

What's wrong with just getting the right index and increasing it?

 for (int i=0;i<myList.Length;i++) { draw_thing(myList[i],myList[++i]); } 

Oops - sorry, in C # mode. I am sure you understand.

-3
source

All Articles