如何替换Python列表的特定索引处的值?

问题描述 投票:0回答:9

如果我有一个清单:

to_modify = [5,4,3,2,1,0]

然后声明另外两个列表:

indexes = [0,1,3,5]
replacements = [0,0,0,0]

如何将

to_modify
的元素作为
indexes
的索引,然后将
to_modify
中对应的元素设置为
replacements
,即运行后,
indexes
应该是
[0,0,3,0,1,0]

显然,我可以通过 for 循环来做到这一点:

for ind in to_modify:
    indexes[to_modify[ind]] = replacements[ind]

但是还有其他方法可以做到这一点吗? 我可以使用

operator.itemgetter
吗?

python arrays slice
9个回答
55
投票

您的代码最大的问题是它不可读。 Python 代码的第一条规则是,如果它不可读,那么没有人会花足够长的时间查看它以从中获取任何有用的信息。始终使用描述性变量名称。差点没发现代码中的错误,让我们用好名字、慢动作重播风格再看一遍:

to_modify = [5,4,3,2,1,0]
indexes = [0,1,3,5]
replacements = [0,0,0,0]

for index in indexes:
    to_modify[indexes[index]] = replacements[index]
    # to_modify[indexes[index]]
    # indexes[index]
    # Yo dawg, I heard you liked indexes, so I put an index inside your indexes
    # so you can go out of bounds while you go out of bounds.

很明显,当您使用描述性变量名称时,您正在使用自身的值对索引列表进行索引,这在这种情况下没有意义。

此外,当并行迭代 2 个列表时,我喜欢使用

zip
函数(或者
izip
如果您担心内存消耗,但我不是那些迭代纯粹主义者之一)。所以试试这个吧。

for (index, replacement) in zip(indexes, replacements):
    to_modify[index] = replacement

如果您的问题仅涉及数字列表,那么我会说@steabert 拥有您正在寻找的 numpy 内容的答案。但是,您不能使用序列或其他可变大小的数据类型作为 numpy 数组的元素,因此,如果您的变量

to_modify
中包含类似的内容,那么您最好使用 for 循环来完成它。


36
投票

numpy 具有允许您使用其他列表/数组作为索引的数组:

import numpy
S=numpy.array(s)
S[a]=m

17
投票

为什么不只是:

map(s.__setitem__, a, m)

3
投票

您可以使用

operator.setitem

from operator import setitem
a = [5, 4, 3, 2, 1, 0]
ell = [0, 1, 3, 5]
m = [0, 0, 0, 0]
for b, c in zip(ell, m):
    setitem(a, b, c)
>>> a
[0, 0, 3, 0, 1, 0]

它比您的解决方案更具可读性或更高效吗?我不确定!


3
投票

有点慢,但我认为可读:

>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d  #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]

2
投票

a 中的索引:

这将导致

index
采用 a
elements
的值,因此将它们用作索引并不是您想要的。在 Python 中,我们通过实际迭代容器来迭代容器。

“但是等等”,你说,“对于

a
的每个元素,我需要使用
m
的相应元素。如果没有索引,我该怎么做?”

简单。我们将

a
m
转换为对列表(来自 a 的元素,来自 m 的元素),并迭代这些对。这很容易做到 - 只需使用内置库函数
zip
,如下所示:

for a_element, m_element in zip(a, m):
  s[a_element] = m_element

为了使其按照您尝试的方式工作,您必须获取要迭代的索引列表。这是可行的:例如我们可以使用

range(len(a))
。但不要这样做!这不是我们在 Python 中做事的方式。实际上直接迭代你想要迭代的东西是一个美丽的、解放思想的想法。

operator.itemgetter 怎么样

与此无关。

operator.itemgetter
的目的是将索引的行为变成某种东西,变成类似函数的东西(我们称之为“可调用”),以便它可以用作回调(例如,排序或最小/最大操作)。如果我们在这里使用它,我们就必须在每次循环中重新调用它来创建一个新的 itemgetter,这样我们就可以立即使用它一次并扔掉它。在上下文中,这只是忙碌的工作。


0
投票

你可以使用字典解决它

to_modify = [5,4,3,2,1,0]
indexes = [0,1,3,5]
replacements = [0,0,0,0]

dic = {}
for i in range(len(indexes)):
    dic[indexes[i]]=replacements[i]
print(dic)

for index, item in enumerate(to_modify):
    for i in indexes:
        to_modify[i]=dic[i]
print(to_modify)

输出将是

{0: 0, 1: 0, 3: 0, 5: 0}
[0, 0, 3, 0, 1, 0]

0
投票
elif menu.lower() == "edit":
    print ("Your games are: "+str (games))
    remove = input("Which one do you want to edit: ")
    add = input("What do you want to change it to: ")
    for i in range(len(games)) :
        if str(games[i]) == str(remove) :
            games[i] = str(add)
            break
        else :
            pass
    pass

为什么不这样使用它呢?直接从删除的位置替换,无论如何,您可以添加数组并执行 .sort .reverse 如果需要


0
投票

新词=[] #错误= 0 对于 myrandomword 中的项目: newword.append(项目) 打印(新词)

#for i in range(0,len(newword)-1,1): myletter = input("请输入您的字母:") 对于索引,枚举中的项目(newword):#con enumerate() otteniamo sia l'indice che il suo valore 如果项目==我的信: 新词[索引] = myletter 别的: 新词[索引] = " " 打印(新词)

© www.soinside.com 2019 - 2024. All rights reserved.