从 Python 列表中的每个数字中减去一个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4918425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:09:11  来源:igfitidea点击:

Subtract a value from every number in a list in Python?

pythonpython-3.x

提问by jaycodez

I have a list

我有一个清单

 a = [49, 51, 53, 56]

How do I subtract 13 from each integer value in the list?

如何从列表中的每个整数值中减去 13?

采纳答案by Ignacio Vazquez-Abrams

With a list comprehension:

使用列表理解

a = [x - 13 for x in a]

回答by Oscar Mederos

This will work:

这将起作用:

for i in range(len(a)):
  a[i] -= 13

回答by shang

If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:

如果你经常使用数字,你可能想看看NumPy。它允许您直接对数值数组执行各种操作。例如:

>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])

回答by sputnikus

You can use map()function:

您可以使用map()函数:

a = list(map(lambda x: x - 13, a))

回答by JJ K.

To clarify an already posted solution due to questions in the comments

由于评论中的问题,澄清已经发布的解决方案

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

将输出:

array([36, 38, 40, 43])

数组([36, 38, 40, 43])