Skip to main content
 首页 » 编程设计

python之在 Python 中用新值替换替换索引中给定位置的列表中的元素

2025年05月04日13mfrbuaa

我想用新值替换替换索引中给定位置的列表中的元素。例如,如果给定列表是 replace_elements([1,2,3,4,5,6,7,8],[0,4,3],0) 那么结果应该是[0、2、3、0、0、6、7、8]。我尝试了几种方法,但似乎都不起作用。我尝试了以下代码:

for i in new_value: 
   list_a[i] = replacement_indices 
return new_value 

请您参考如下方法:

TL;DR:一种不能就地工作的列表理解方法:

只需根据列表理解中的索引在三元表达式中决定替换值还是原始值:

def replace_elements(inlist, indexes, replvalue): 
    return [replvalue if i in indexes else x for i,x in enumerate(inlist)] 
 
print(replace_elements([1,2,3,4,5,6,7,8],[0,4,3],0)) 

结果:

[0, 2, 3, 0, 0, 6, 7, 8] 

对于大索引列表,[0,4,3] 应该是一个集合 ({0,4,3})更快的查找。