How to get the elements of a list by pairs in python [closed]

3

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)]
    
asked by Carlos Cardoso 04.09.2016 в 20:54
source

2 answers

1

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)
answered by 05.09.2016 / 00:14
source
4

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)]
    
answered by 04.09.2016 в 21:31