简体   繁体   English

添加一个数字以在指定的索引范围内列出

[英]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.

相关问题 删除链接列表的指定索引范围内的项目 - Deleting items in a specified index range for linked list 尝试将列表中的数字添加到另一个列表时出现列表索引超出范围错误 - getting list index out of range error when trying to add a a number from a list into a another list 如何在熊猫数组的索引范围内添加数字 - How to add a number to an index range of a pandas array 如果列表索引不在范围内,请在Python中用数字索引列表 - Index a list in Python with number if list index not outside of range 在python 3中超出索引范围的索引处将元素添加到列表 - Add an element to a list at an index that is out of range in python 3 查找某个数字是否存在于列表指定的数字范围之间 - Find if a number exists between a range of numbers specified by a list IndexError:当指定的值在列表范围内时,会显示超出范围的列表索引 - IndexError: list index out of range shows up when the value specified is inside the range of the list 列出索引超出范围和随机数以选择列表中的项目 - List index out of range and random number to choose an item in list List Comprehension Appending Index with Number Range on Lists - List Comprehension Appending Index with Number Range on List of Lists 如何将数字添加到列表中的某个索引? - How to add a number to a certain index in a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM