【问题标题】:Replacing the elements in list at the positions given in replacement indices with new value in Python在Python中用新值替换替换索引中给定位置的列表中的元素
【发布时间】:2019-05-12 18:32:50
【问题描述】:

我想用新值替换替换索引中给定位置的列表中的元素。例如,如果给定列表是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

【问题讨论】:

  • @jpp 更像是重复的,对吧?你可以关闭我不会大喊大叫
  • @Jean-FrançoisFabre,IMO 略有不同,因为该帖子支持每个索引的不同值。虽然这对list 无关紧要,但对 NumPy 可能很重要(例如)。并不是说我建议我们在这里提供 NumPy 解决方案 :)。

标签: python


【解决方案1】:

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] 应该是 set ({0,4,3}) 以便更快地查找。

【讨论】:

  • 最后一行在这里很重要!
  • 也就是说,一个简单的就地循环不需要set
【解决方案2】:

您将replacment_indicesnew_value 放在了错误的位置。您应该遍历 replacement_indices 并将 new_value 分配给每个指定索引处的列表:

for i in replacement_indices:
   list_a[i] = new_value

由于您正在就地修改列表,因此也无需返回任何内容,这意味着在循环之后 list_a 将根据规范进行修改。

【讨论】:

  • return new_value 是罪魁祸首。这段代码就地工作
  • 这不像我的那样炫耀,因为它不使用set,但似乎是最合乎逻辑的
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 2015-12-29
  • 2018-01-11
  • 1970-01-01
  • 2016-01-06
  • 2016-04-03
相关资源
最近更新 更多