问题图片
他们在“= -1”的部分失去了我
这是我对解决方案的理解(到目前为止)。他们使用 arr 变量并扫描除以 2 时余数为 1 的元素。 = -1 部分是我感到困惑的地方。
另外,这种特殊的技术叫什么?
编辑:所以我尝试了他们提供的解决方案,它甚至没有运行......不确定我是否做错了什么。
Original site link: Source
Just like anything else you're trying to understand, take it step by step. Try printing out each of these intermediate expressions:
arr
is a numpy array. This is important, because all of these steps depend on special numpy features - they wouldn't work on an ordinary list.arr % 2
is an array of the same size, containing the parity of each of the original numbers - 0 for even, 1 for odd.arr % 2 == 1
turns that into an array of booleans - False for even, True for odd.arr[arr % 2 == 1]
invokes numpy's special boolean indexing feature - it gives you a view of a (possibly discontiguous) subset of the array, wherever the index value was True. In this case, the view contains only the odd numbers of the original array.arr[arr % 2 == 1] = -1
assigns the same value to each element in the view, overwriting all of the original odd numbers.在所有步骤中使用的一个关键 numpy 概念是“广播”——基本上,每当尝试在数组和单个元素之间进行操作时,单个元素都会被有效地复制以匹配数组的大小。因此,在 中arr % 2
,2
理论上变成了2
s的数组,大小与 相同arr
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句