Cómo combinar listas en una lista de tuplas?


¿Cuál es el enfoque pitónico para lograr lo siguiente?

# Original lists:

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

# List of tuples from 'list_a' and 'list_b':

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

Cada miembro de list_c es una tupla, cuyo primer miembro es de list_a y el segundo es de list_b.

Author: martineau, 2010-03-09

8 answers

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a, list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
 304
Author: YOU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-27 15:13:36

En python 3.0 zip devuelve un objeto zip. Puede obtener una lista llamando a list(zip(a, b)).

 115
Author: Lodewijk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-27 15:13:45

Estás buscando la función incorporada zip.

 8
Author: Mizipzor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-09 07:55:50

Puede usar el mapa lambda

a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)

Esto también funcionará si las longitudes de las listas originales no coinciden

 8
Author: Dark Knight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-04 05:49:00

Sé que esta es una vieja pregunta y ya fue respondida, pero por alguna razón, todavía quiero publicar esta solución alternativa. Sé que es fácil averiguar qué función incorporada hace la "magia" que necesita, pero no está de más saber que puede hacerlo usted mismo.

>>> list_1 = ['Ace', 'King']
>>> list_2 = ['Spades', 'Clubs', 'Diamonds']
>>> deck = []
>>> for i in range(max((len(list_1),len(list_2)))):
        while True:
            try:
                card = (list_1[i],list_2[i])
            except IndexError:
                if len(list_1)>len(list_2):
                    list_2.append('')
                    card = (list_1[i],list_2[i])
                elif len(list_1)<len(list_2):
                    list_1.append('')
                    card = (list_1[i], list_2[i])
                continue
            deck.append(card)
            break
>>>
>>> #and the result should be:
>>> print deck
>>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')]
 5
Author: Kruger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-17 12:58:17

La salida que mostró en la instrucción problem no es la tupla sino la lista

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

Compruebe

type(list_c)

Considerando que desea el resultado como tupla fuera de list_a y list_b, haga

tuple(zip(list_a,list_b)) 
 4
Author: cyborg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-12 14:52:22

Una alternativa sin usar zip:

list_c = [(p1, p2) for idx1, p1 in enumerate(list_a) for idx2, p2 in enumerate(list_b) if idx1==idx2]

En caso de que uno quiera obtener no solo tuplas 1st con 1st, 2nd con 2nd... pero todas las combinaciones posibles de las 2 listas, que se haría con

list_d = [(p1, p2) for p1 in list_a for p2 in list_b]
 0
Author: J0ANMM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 13:57:41

No estoy seguro si esto es una forma pitónica o no, pero esto parece simple si ambas listas tienen el mismo número de elementos :

list_a = [1, 2, 3, 4]

list_b = [5, 6, 7, 8]

list_c=[(list_a[i],list_b[i]) for i in range(0,len(list_a))]
 0
Author: Vipin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 09:01:28