如何替换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.