I have this list in python
[a,b,c,d,e,f,g,h]
How can I get the elements by pairs stored in a list of tuples. In this way:
[(a,b),(c,d),(e,f),(g,h)]
I have this list in python
[a,b,c,d,e,f,g,h]
How can I get the elements by pairs stored in a list of tuples. In this way:
[(a,b),(c,d),(e,f),(g,h)]
A generic solution to obtain tuples of N
items from a list:
def troceo(lista, n):
return list(zip(*[iter(lista)]*n))
Explanation by parts:
iter(lista)
gets an iterator from the list [iter(lista)]*n
creates a list of length n
using the same repeated iterator zip(*[iter(lista)]*n)
passes the list as an argument, equivalent to passing n
times the iterator. That is, zip(*[it]*2)
equals zip(it,it)
list(zip(*[iter(lista)]*n))
convert the result to a list (in python3, zip returns another iterator) I was able to solve it using the zip function.
lista = [a,b,c,d,e,f,g,h]
Generation of a list consisting of tuples using the zip function
zipped = zip(lista[0::2], lista[1::2])
Result for zipped:
[(a,b),(c,d),(e,f),(g,h)]