Sum one number to every element in a list (or array) in Python

后端 未结 5 2214
悲&欢浪女
悲&欢浪女 2020-12-08 04:34

Here I go with my basic questions again, but please bear with me.

In Matlab, is fairly simple to add a number to elements in a list:

a = [1,1,1,1,1]
         


        
相关标签:
5条回答
  • 2020-12-08 04:50

    You can also use map:

    a = [1, 1, 1, 1, 1]
    b = 1
    list(map(lambda x: x + b, a))
    

    It gives:

    [2, 2, 2, 2, 2]
    
    0 讨论(0)
  • 2020-12-08 04:51

    if you want to operate with list of numbers it is better to use NumPy arrays:

    import numpy
    a = [1, 1, 1 ,1, 1]
    ar = numpy.array(a)
    print ar + 2
    

    gives

    [3, 3, 3, 3, 3]
    
    0 讨论(0)
  • 2020-12-08 05:03

    try this. (I modified the example on the purpose of making it non trivial)

    import operator
    import numpy as np
    
    n=10
    a = list(range(n))
    a1 = [1]*len(a)
    an = np.array(a)
    

    operator.add is almost more than two times faster

    %timeit map(operator.add, a, a1)
    

    than adding with numpy

    %timeit an+1
    
    0 讨论(0)
  • 2020-12-08 05:07

    If you don't want list comprehensions:

    a = [1,1,1,1,1]
    b = []
    for i in a:
        b.append(i+1)
    
    0 讨论(0)
  • 2020-12-08 05:08

    using List Comprehension:

    >>> L = [1]*5
    >>> [x+1 for x in L]
    [2, 2, 2, 2, 2]
    >>> 
    

    which roughly translates to using a for loop:

    >>> newL = []
    >>> for x in L:
    ...     newL+=[x+1]
    ... 
    >>> newL
    [2, 2, 2, 2, 2]
    

    or using map:

    >>> map(lambda x:x+1, L)
    [2, 2, 2, 2, 2]
    >>> 
    
    0 讨论(0)
提交回复
热议问题