Doing bulk arithmetic on a python list

I have a list of integers and I want to efficiently perform operations such as addition, multiplication, division of sexes on each element of the slice (sub array) list or on specific indices (e.g. range (start, end, jump)). The number added to or multiplied by each item in the slice of the list is constant (for example, "k").

For example:

    nums = [23, 44, 65, 78, 87, 11, 33, 44, 3]
    for i in range(2, 7, 2):
        nums[i] //= 2 # here 2 is the constant 'k'
    print(nums)
    >>>    [23, 44, 32, 78, 43, 11, 16, 44, 3]

      

I have to perform these operations several times on different sections / ranges, and the constant "k" changes for different segments / ranges. The obvious way to do this is to start a for loop and change the value of the elements, but this is not fast enough. You can do this efficiently using a numpy array because it supports mass assignment / modification, but I am looking for a way to do this in pure python.

+3


source to share


1 answer


One way to avoid the for loop is as follows:



>>> nums = [23, 44, 65, 78, 87, 11, 33, 44, 3]
>>> nums[2:7:2] = [x//2 for x in nums[2:7:2]]
>>> nums
[23, 44, 32, 78, 43, 11, 16, 44, 3]

      

0


source







All Articles