Iterar sobre todas las combinaciones de valores en múltiples listas en Python


Dada la lista múltiple de longitud posiblemente variable, quiero iterar sobre todas las combinaciones de valores, un elemento de cada lista. Por ejemplo:

first = [1, 5, 8]
second = [0.5, 4]

Entonces quiero que la salida de sea:

combined = [(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]

Quiero iterar sobre la lista combinada. ¿Cómo hago esto?

Author: Martin Thoma, 2013-05-05

2 answers

itertools.product debería funcionar.

>>> list(itertools.product([1, 5, 8], [0.5, 4]))
[(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]

Tenga en cuenta que itertools.product devuelve un iterador, por lo que no necesita convertirlo en una lista si solo va a iterar sobre él una vez.

Eg.

for x in itertools.product([1, 5, 8], [0.5, 4]):
    # do stuff
 59
Author: Volatility,
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
2013-05-05 11:40:41

Esto se puede lograr sin ninguna importación utilizando una comprensión de lista . Usando su ejemplo:

first = [1, 5, 8]
second = [0.5, 4]

combined = [(f,s) for f in first for s in second]

print(combined)
# [(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]
 2
Author: spinup,
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-04-28 01:42:54