简体   繁体   English

在python列表上执行批量算术运算

[英]Performing bulk arithmetic operations on python list

I have a list of integers and I want to perform operations like addition, multiplication, floor division on every element of list slice (sub array) or at certain indexes (eg. range(start, end, jump) ) efficiently. 我有一个整数列表,我想有效地对列表切片(子数组)的每个元素或某些索引(例如范围(开始,结束,跳转))执行加法,乘法,平面除法等操作。 The number being added or multiplied by each element of list slice is constant (say 'k'). 列表切片的每个元素添加或乘以的数字是常量(比如'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 slices/ranges and the constant 'k' varies for different slices/ranges. 我必须在不同的切片/范围上多次执行这些操作,并且常数“k”因不同的切片/范围而变化。 The obvious way to do this is to run a for loop and modify the value of elements, but that isn't fast enough. 显而易见的方法是运行for循环并修改元素的值,但这还不够快。 You can do this efficiently by using a numpy array because it supports bulk assignment/modification but I am looking for a way to do this in pure python. 您可以通过使用numpy数组来有效地执行此操作,因为它支持批量分配/修改,但我正在寻找一种在纯python中执行此操作的方法。

One way to avoid the for loop is the following: 避免for循环的一种方法如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM