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

前端 未结 5 932
耶瑟儿~
耶瑟儿~ 2020-12-04 17:16

I have a list

 a = [49, 51, 53, 56]

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

相关标签:
5条回答
  • 2020-12-04 17:42

    With a list comprehension:

    a = [x - 13 for x in a]
    
    0 讨论(0)
  • 2020-12-04 17:43

    This will work:

    for i in range(len(a)):
      a[i] -= 13
    
    0 讨论(0)
  • 2020-12-04 17:44

    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:

    >>> import numpy
    >>> array = numpy.array([49, 51, 53, 56])
    >>> array - 13
    array([36, 38, 40, 43])
    
    0 讨论(0)
  • 2020-12-04 17:47

    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])

    0 讨论(0)
  • 2020-12-04 17:54

    You can use map() function:

    a = list(map(lambda x: x - 13, a))
    
    0 讨论(0)
提交回复
热议问题