使用&在python中的if语句中
在解决其中一个问题的同时,我发现了一种奇怪的行为。
def sortedSquares(nums: list[int]) -> list[int]:
pointer = len(nums) - 1
for i in range(pointer):
if nums[pointer] > abs(nums[0]) & nums[pointer-1] < abs(nums[0]):
nums.insert(pointer, abs(nums[0]))
nums.remove(nums[0])
pointer -= 1
elif nums[pointer] < abs(nums[0]):
nums.insert(pointer+1, abs(nums[0]))
nums.remove(nums[0])
pointer -= 1
else:
pointer -= 1
return [num ** 2 for num in nums]
它在以下输入示例中很好地工作:
assert sortedSquares([-5, -3, -2, -1]) == [1, 4, 9, 25]
但是它不起作用:以
assert sortedSquares([-3, 0, 2]) == [0, 4, 9]
某种方式,ELIF语句在第一次迭代中被跳过。但是,当我更改了位&amp;逻辑和if语句中的操作员开始工作。
有人可以解释一下这里发生了什么吗?
对不起,如果这是重复的。我一直在试图找到一个解释,但什么也没找到。
While solving one of the problems, I found a strange behavior.
def sortedSquares(nums: list[int]) -> list[int]:
pointer = len(nums) - 1
for i in range(pointer):
if nums[pointer] > abs(nums[0]) & nums[pointer-1] < abs(nums[0]):
nums.insert(pointer, abs(nums[0]))
nums.remove(nums[0])
pointer -= 1
elif nums[pointer] < abs(nums[0]):
nums.insert(pointer+1, abs(nums[0]))
nums.remove(nums[0])
pointer -= 1
else:
pointer -= 1
return [num ** 2 for num in nums]
It's working fine for the following input example:
assert sortedSquares([-5, -3, -2, -1]) == [1, 4, 9, 25]
But it's not working for this:
assert sortedSquares([-3, 0, 2]) == [0, 4, 9]
Somehow the ELIF statement was skipped during the first iteration. But when I changed bitwise & operator to logical AND in the IF statement - it started to work.
Could someone please explain what's going on here?
Sorry if it's a duplicate. I have been trying to find an explanation but found nothing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
行为并不奇怪。您应该检查操作员优先。您错过了
(...)&amp; (...)
:应
输出
The behavior is not strange. You should check Operator precedence. You missed
(...) & (...)
:should be
Output
如 documentation ,
/代码>比
&gt;
和&lt;
具有更高的优先级。因此,对使用(正确)逻辑
和
时的评估与哪些不同,因为它的优先级低于
&gt;
and and&lt; ,因此声明会按照您的期望为:
As described in the documentation,
&
has higher precedence than>
and<
. Thusis evaluated as
which is not the same as when you use (the correct) logical
and
, as that has lower precedence than>
and<
and thus the statement evaluates as you expect as: