Python 如何基于要替换的值的数组将数组中的值归零
我有一个带值的数组sourceArray,我有一个带值的数组来替换toReplace。我要替换sourceArray中与toReplace数组中的值相等的所有值 在Python中是否有一些聪明的方法可以做到这一点 例如 更换后,我想有Python 如何基于要替换的值的数组将数组中的值归零,python,Python,我有一个带值的数组sourceArray,我有一个带值的数组来替换toReplace。我要替换sourceArray中与toReplace数组中的值相等的所有值 在Python中是否有一些聪明的方法可以做到这一点 例如 更换后,我想有 sourceArray = [0,1,2,3,4,0,0,0,7] 使用条件表达式列出理解: [0 if i in toReplace else i for i in sourceArray] 如果toReplace列表太大,最好将其设置为set,以获得O(
sourceArray = [0,1,2,3,4,0,0,0,7]
使用条件表达式列出理解:
[0 if i in toReplace else i for i in sourceArray]
如果toReplace
列表太大,最好将其设置为set
,以获得O(1)查找
示例:
In [21]: sourceArray = [0,1,2,3,4,5,5,6,7]
...: toReplace = [5,6]
...:
In [22]: [0 if i in toReplace else i for i in sourceArray]
Out[22]: [0, 1, 2, 3, 4, 0, 0, 0, 7]
您可以使用列表理解:
new_list = [x if toReplace.count(x)==0 else 0 for x in sourceArray]
为什么不在第一个数组(sourceArray)上迭代,当索引i==toReplaceArray[j]时,将其转换为0?在这里,您需要一个循环和一个内部循环*我觉得在Python中有一种更聪明的方法:)
new_list = [x if toReplace.count(x)==0 else 0 for x in sourceArray]