python 整数比较确实很尴尬(看似简单)的错误

发布于 2024-09-11 03:06:49 字数 784 浏览 7 评论 0原文

我有以下一段代码,它根本没有按照我期望的方式工作...

current_frame = 15 # just for showcasing purposes
g_ch = 7

if (current_frame != int(row[0])) and (int(row[1]) != g_ch):
                current_frame = int(row[0])
                print "curious================================="
                print current_frame
                print row
                print current_frame, " != ", int(row[0]), ", ", current_frame != int(row[0])
                print "========================================"

它针对任何特定情况进行打印:

curious================================= 

15 

['15', '1', 'more data'] 15 != 15 , False

========================================

显然,这甚至不应该输入 if 语句,因为相等性显示为 false。为什么会发生这种情况?

编辑:我也尝试过用 != 而不是“不是”,并得到了相同的结果。

I have the following piece of code which is not working the way I expect it to at all...

current_frame = 15 # just for showcasing purposes
g_ch = 7

if (current_frame != int(row[0])) and (int(row[1]) != g_ch):
                current_frame = int(row[0])
                print "curious================================="
                print current_frame
                print row
                print current_frame, " != ", int(row[0]), ", ", current_frame != int(row[0])
                print "========================================"

which prints for any specific case:

curious================================= 

15 

['15', '1', 'more data'] 15 != 15 , False

========================================

This should obviously never even enter the if statement, as the equality is showing false. Why is this happening?

edit: I have also tried this with != instead of 'is not', and gotten the same results.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橘亓 2024-09-18 03:06:49

值比较是使用 != 运算符完成的,而不是使用 is not 来完成的,后者比较对象标识。

除此之外,我认为这是一个缩进问题。

Value comparisons are done with the != operator, not with is not, which compares object identity.

Apart from that, I think it's an indentation problem.

亢潮 2024-09-18 03:06:49

简而言之,您需要使用 ==!=,而不是 isis 比较对象同一性,而不是相等性。

In short, you need to use == and !=, and not is. is compares object identity, not equality.

浴红衣 2024-09-18 03:06:49

您可以在 if 内指定 current_frame = int(row[0]),这会更改布尔表达式的值。

You assign current_frame = int(row[0]) inside the if, which changes the value of the boolean expression.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文