Restar un valor de cada número en una lista en Python?


Todavía estoy leyendo el tutorial de Python 3.1.3 y encontré el siguiente problema:

¿Cómo se elimina un valor de un grupo de números?

# A list with a group of values
a = [49, 51, 53, 56]

¿Cómo resto 13 de cada valor entero en la lista?

# Attempting to minus 13 from this list - FAIL!
(a[:] = a[:] - 13)
Author: Mirzhan Irkegulov, 2011-02-07

4 answers

Con una lista de comprensión.

a[:] = [x - 13 for x in a]
 86
Author: Ignacio Vazquez-Abrams,
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
2011-02-07 05:56:30

Si está trabajando mucho con números, es posible que desee echar un vistazo a NumPy. Le permite realizar todo tipo de operaciones directamente en matrices numéricas. Por ejemplo:

>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])
 46
Author: shang,
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
2011-02-07 07:35:49

Puedes usar la función map () :

a = list(map(lambda x: x - 13, a))
 8
Author: sputnikus,
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
2011-02-07 08:31:14

Esto funcionará:

for i in range(len(a)):
  a[i] -= 13
 2
Author: Oscar Mederos,
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
2011-02-07 05:58:34