Cómo multiplicar todos los enteros dentro de la lista [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Hola, quiero multiplicar los enteros dentro de una lista.

Por ejemplo;

l = [1, 2, 3]
l = [1*2, 2*2, 3*2]

Salida:

l = [2, 4, 6]

Así que estaba buscando en línea y la mayoría de las respuestas se referían a multiplicar todos los números enteros con entre sí tales como:

[1*2*3]

Author: roadrunner66, 2014-10-19

6 answers

Prueba una lista comprensión :

l = [x * 2 for x in l]

Esto pasa por l, multiplicando cada elemento por dos.

Por supuesto, hay más de una manera de hacerlo. Si estás en funciones lambda y map, usted puede incluso hacer

l = map(lambda x: x * 2, l)

Para aplicar la función lambda x: x * 2 a cada elemento en l. Esto es equivalente a:

def timesTwo(x):
    return x * 2

l = map(timesTwo, l)
 49
Author: APerson,
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-10-19 01:36:25

La forma más pitónica sería usar una comprensión de lista:

l = [2*x for x in l]

Si necesita hacer esto para un gran número de enteros, use numpy arrays:

l = numpy.array(l, dtype=int)*2

Una alternativa final es usar map

l = list(map(lambda x:2*x, l))
 12
Author: Joshua,
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-10-19 01:44:11

Otro enfoque funcional que es quizás un poco más fácil de mirar que una función anónima si vas por esa ruta es usar functools.partial para utilizar el parámetro de dos operator.mul con un múltiplo fijo

>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
 4
Author: miradulo,
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-25 11:51:54

La forma más sencilla para mí es:

map((2).__mul__, [1, 2, 3])
 3
Author: blameless75,
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
2017-04-03 13:28:25
#multiplying each element in the list and adding it into an empty list
original = [1, 2, 3]
results = []
for num in original:
    results.append(num*2)# multiply each iterative number by 2 and add it to the empty list.

print(results)
 1
Author: Jonathan Akwetey Okine,
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
2017-11-27 02:25:01

Usando numpy:

    In [1]: import numpy as np

    In [2]: nums = np.array([1,2,3])*2

    In [3]: nums.tolist()
    Out[4]: [2, 4, 6]
 0
Author: ilya shusterman,
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-01-19 06:29:30