列表的逻辑索引 [英] Logical indexing with lists
本文介绍了列表的逻辑索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
本节中有我正在浏览的程序
I have a program I'm looking through and with this section
temp = [1,2,3,4,5,6]
temp[temp!=1]=0
print temp
如果运行将给出结果:
[1, 0, 3, 4, 5, 6]
我需要帮助来理解这段代码中导致结果的事情.
I need help understanding what is going on in this code that leads to this result.
推荐答案
正如已经说明的,您正在使用与返回True/1作为 bool是int的子类.您有一个列表而不是一个numpy数组,因此如果要更改它,则需要对其进行迭代,这可以使用 if/els e逻辑使用列表理解来完成:
As Already explained you are setting the second element using the result of comparing to a list which returns True/1 as bool is a subclass of int. You have a list not a numpy array so you need to iterate over it if you want to change it which you can do with a list comprehension using if/else logic:
temp = [1,2,3,4,5,6]
temp[:] = [0 if ele != 1 else ele for ele in temp ]
哪个会给你:
[1, 0, 0, 0, 0, 0]
或使用生成器表达式:
temp[:] = (0 if ele != 1 else ele for ele in temp)
这篇关于列表的逻辑索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文