python - 递增列表切片的最快方法是什么?

标签 python

我有一个列表:

lst = [ 1,2,3,4,5,6,7,8]

我想递增索引 4 以上的所有数字。

for i in range(4,len(lst)):
    lst[i]+=2

由于这个操作需要多次完成,所以我想以最有效的方式进行。 我怎样才能快速做到这一点。

最佳答案

使用Numpy对于快速数组操作,请查看以下示例:

import numpy as np

lst = np.array([1,2,3,4,5,6,7,8])

# add 2 at all indices from 4 till the end of the array
lst[4:] += 2

print(lst)
# array([ 1,  2,  3,  4,  7,  8,  9, 10])

关于python - 递增列表切片的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59448954/

相关文章:

python - 在 python 文件中查找有机会执行的语句

python - 在文件上传的情况下,django form.is_valid() 始终返回 0

python - 我无法仅在模板中将 bool 字段设置为 true 时显示帖子

python - 如何在 Python(在 DOS 上)中捕获 shutil.copy() 的返回值?

python - QSound 在对象内部的意外行为

python - sqlanydb windows 无法加载 dbcapi

python - 功能等同于 Python 语句逻辑

python - 使用 Python 进行图像变形

python - 如何使用python在sql中选择一长串id

python - 为什么 Python 在 if 语句中将字符串/数字评估为 True 而 myNumber == True 返回 False?