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

查看:1924
本文介绍了如何替换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代码规则第一,如果它不可读,没人会花很长时间查看它,以从中获取任何有用的信息.始终使用描述性变量名.几乎没有发现代码中的错误,让我们以好名字,慢动作重播的方式再次查看它:

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天全站免登陆