[英]Add a number to list in a specified index range
Input输入
l = [0, 0, 1, 2, 3]
I want to add 1 to index range from 2 to 3我想将 1 添加到索引范围从 2 到 3
so output should be所以输出应该是
l = [0, 0, 2, 3, 3]
l[2:3] = l[2:3] + 1
The easiest way would be to use numpy
, it's quite optimized and uses C/C++ loops under the hood, so it's blazingly fast:最简单的方法是使用
numpy
,它已经过优化,并且在numpy
使用了 C/C++ 循环,因此速度非常快:
>>> import numpy as np
>>> a = [0, 0, 1, 2, 3]
>>> b = np.array(a)
>>> b[2:4] += 1
>>> b
array([0, 0, 2, 3, 3])
>>>
You can try this:你可以试试这个:
for i in range(2, 4):
l[i] += 1
一个可能的解决方案可以使用列表理解: l[2:4] = [x+1 for x in l[2:4]]
For a hilariously overblown solution:对于一个非常夸张的解决方案:
from operator import add
l = [0, 0, 1, 2, 3]
deltas = [0, 0, 1, 1, 1]
result = list(map(add, l, deltas))
note that this does not modify l
, but creates a new list in result
请注意,这不会修改
l
,而是在result
创建一个新列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.