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

发布于 2024-12-02 10:35:46 字数 559 浏览 3 评论 0原文

如果我有一个列表:

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

然后声明另外两个列表:

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

如何将 to_modify 的元素作为 indexes 的索引,然后在 to_modify< 中设置相应的元素/code> 为 replacements,即运行后,indexes 应为 [0,0,3,0,1,0]

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

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

但是还有其他方法可以做到这一点吗? 我可以以某种方式使用 operator.itemgetter 吗?

If I have a list:

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

And then declare two other lists:

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

How can I take to_modify's elements as index to indexes, then set corresponding elements in to_modify to replacements, i.e. after running, indexes should be [0,0,3,0,1,0].

Apparently, I can do this through a for loop:

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

But is there other way to do this?
Could I use operator.itemgetter somehow?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

深府石板幽径 2024-12-09 10:35:46

您的代码最大的问题是它不可读。 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 数组的元素,因此,如果您的变量 to_modify 中有类似的内容,您可能最好使用 for 来执行此操作环形。

The biggest problem with your code is that it's unreadable. Python code rule number one, if it's not readable, no one's gonna look at it for long enough to get any useful information out of it. Always use descriptive variable names. Almost didn't catch the bug in your code, let's see it again with good names, slow-motion replay style:

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.

As is obvious when you use descriptive variable names, you're indexing the list of indexes with values from itself, which doesn't make sense in this case.

Also when iterating through 2 lists in parallel I like to use the zip function (or izip if you're worried about memory consumption, but I'm not one of those iteration purists). So try this instead.

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

If your problem is only working with lists of numbers then I'd say that @steabert has the answer you were looking for with that numpy stuff. However you can't use sequences or other variable-sized data types as elements of numpy arrays, so if your variable to_modify has anything like that in it, you're probably best off doing it with a for loop.

老子叫无熙 2024-12-09 10:35:46

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

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

numpy has arrays that allow you to use other lists/arrays as indices:

import numpy
S=numpy.array(s)
S[a]=m
纵情客 2024-12-09 10:35:46

为什么不只是:

map(s.__setitem__, a, m)

Why not just:

map(s.__setitem__, a, m)
心奴独伤 2024-12-09 10:35:46

您可以使用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]

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

You can use 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]

Is it any more readable or efficient than your solution? I am not sure!

寄离 2024-12-09 10:35:46

有点慢,但我认为可读:

>>> 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]

A little slower, but readable I think:

>>> 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]
魔法少女 2024-12-09 10:35:46

对于a中的索引:

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

“但是等等”,你说,“对于 a 的每个元素,我需要使用 m 的相应元素。如果没有,我该怎么做?指数?”

简单的。我们将 am 转换为对列表(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,这样我们就可以立即使用它一次并扔掉它。从上下文来看,这只是忙碌的工作。

for index in a:

This will cause index to take on the values of the elements of a, so using them as indices is not what you want. In Python, we iterate over a container by actually iterating over it.

"But wait", you say, "For each of those elements of a, I need to work with the corresponding element of m. How am I supposed to do that without indices?"

Simple. We transform a and m into a list of pairs (element from a, element from m), and iterate over the pairs. Which is easy to do - just use the built-in library function zip, as follows:

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

To make it work the way you were trying to do it, you would have to get a list of indices to iterate over. This is doable: we can use range(len(a)) for example. But don't do that! That's not how we do things in Python. Actually directly iterating over what you want to iterate over is a beautiful, mind-liberating idea.

what about operator.itemgetter

Not really relevant here. The purpose of operator.itemgetter is to turn the act of indexing into something, into a function-like thing (what we call "a callable"), so that it can be used as a callback (for example, a 'key' for sorting or min/max operations). If we used it here, we'd have to re-call it every time through the loop to create a new itemgetter, just so that we could immediately use it once and throw it away. In context, that's just busy-work.

桃扇骨 2024-12-09 10:35:46

您可以使用字典解决它,

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]

You can solve it using dictionary

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)

The output will be

{0: 0, 1: 0, 3: 0, 5: 0}
[0, 0, 3, 0, 1, 0]
南烟 2024-12-09 10:35:46
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

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

why not use it like this? replace directly from where it was removed and anyway you can add arrays and the do .sort the .reverse if needed

挥剑断情 2024-12-09 10:35:46
newword = []
#errors = 0
for item in myrandomword:
    newword.append(item)
print(newword)

#for i in range(0,len(newword)-1,1):
myletter =  input("Enter your letter: ")
for index, item in enumerate(newword):  #con enumerate() otteniamo sia l'indice che il suo valore
    if item == myletter:
        newword[index] = myletter
    else:
        newword[index] = " "
print(newword)
newword = []
#errors = 0
for item in myrandomword:
    newword.append(item)
print(newword)

#for i in range(0,len(newword)-1,1):
myletter =  input("Enter your letter: ")
for index, item in enumerate(newword):  #con enumerate() otteniamo sia l'indice che il suo valore
    if item == myletter:
        newword[index] = myletter
    else:
        newword[index] = " "
print(newword)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文