如何替换python列表特定索引处的值? [英] How to replace values at specific indexes of a python list?

查看:106
本文介绍了如何替换python列表特定索引处的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个列表:

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

然后声明另外两个列表:

And then declare two other lists:

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

如何将to_modify的元素作为indexes的索引,然后将to_modify中对应的元素设置为replacements,即运行后indexes应该是[0,0,3,0,1,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].

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

Apparently, I can do this through a for loop:

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

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

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

推荐答案

你的代码最大的问题是它不可读.Python 代码规则第一,如果它不可读,没有人会看它足够长的时间来从中获取任何有用的信息.始终使用描述性变量名称.差点没抓到你代码中的bug,让我们用好名字、慢动作回放风格再看一遍:

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.

此外,当并行迭代 2 个列表时,我喜欢使用 zip 函数(或 izip 如果您担心内存消耗,但我不是其中之一那些迭代纯粹主义者).所以试试这个吧.

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

如果您的问题仅适用于数字列表,那么我会说@steabert 有您正在寻找的那些 numpy 东西的答案.但是,您不能使用序列或其他可变大小的数据类型作为 numpy 数组的元素,因此如果您的变量 to_modify 中包含类似内容,则最好使用 for循环.

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.

这篇关于如何替换python列表特定索引处的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆