简体   繁体   English

在python中,1, 2 == 1, 2是什么意思?

[英]In python, What does this means 1, 2 == 1, 2?

Can someone explain output?有人可以解释输出吗? I wanted to check for equality of two numbers but didn't work out properly.我想检查两个数字是否相等,但没有正确计算。

Input: 1, 2 == 1, 2
Output: (1, False, 2)

You are creating a tuple with 3 elements, namely, 1 , 2 == 1 , and 2 .您正在创建一个包含 3 个元素的元组,即12 == 12 The first and last element are integer literals so it might not come as a surprise that their values in Python evaluate to 1 and 2 respectively.第一个和最后一个元素是整数文字,因此它们在 Python 中的值分别为12可能不足为奇。 The element, 2 == 1 is a single expression that evaluates to False because 2 does not equal 1 .元素2 == 1是一个计算结果为False的单个表达式,因为2不等于1

If you are looking to check the equality of two tuples with two elements, (1,2) and (1,2) you must do (1, 2) == (1, 2) so Python knows which elements separated by commas to treat as a single element.如果要检查具有两个元素(1,2)(1,2)的两个元组的相等性,则必须执行(1, 2) == (1, 2)以便 Python 知道哪些元素以逗号分隔视为单个元素。

In the REPL you can figure this out by comparing what you have with在 REPL 中,您可以通过比较您拥有的内容来弄清楚这一点

>>> (1, 2) == (1, 2)
True
>>> (1, 3) == (1, 2)
False
>>> (3, 1) == (2, 1)
False

You are making a tuple of 3 elements, int, boolean and int.您正在制作一个由 3 个元素组成的元组,int、boolean 和 int。

If you want a simutaneous comparison use如果你想同时比较使用

[1, 2] == [1, 2]
print 1, 2 == 1, 2

which is这是

print 1, False, 2 //since 1 not equal to 2

which will output这将输出

1 False 2 1 错误 2

Actually 2==1 will give you false since 2 is not equal to one.So a better way of doing this is using if statements实际上 2==1 会给你错误,因为 2 不等于 1。所以更好的方法是使用 if 语句

a = 1
b = 2
if b > a:
  print(b + " is greater than " + a)
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

As per your code, it is a simple equality checking.根据您的代码,这是一个简单的相等性检查。 It returns true if both the operands are true, in your case, it is 1 == 2 so it will return false as both are not the same.如果两个操作数都为真,则返回真,在您的情况下,它是 1 == 2,因此它将返回假,因为两者都不相同。 If you to compare them then add braces over them.如果要比较它们,则在它们上面加上大括号。

The order of operations is not what you think.操作顺序不是你想的那样。 == has a higher priority than the commas. == 的优先级高于逗号。 So you are creating a 3-tuple with the following elements:因此,您正在创建一个包含以下元素的 3 元组:

1
the result of the Boolean test to see whether 2 equals 1
2

This may be what you intend, try it:这可能是你想要的,试试吧:

>>> (1,2) == (1,2)
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM