Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我有两个元组比较。几乎相同的数据。为什么会出现此错误:_Python_Tuples - Fatal编程技术网

Python 我有两个元组比较。几乎相同的数据。为什么会出现此错误:

Python 我有两个元组比较。几乎相同的数据。为什么会出现此错误:,python,tuples,Python,Tuples,结果: print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') ) print( ('abc', 1, 2) > ('abc', 1, 'ssst..') ) True 回溯(最近一次呼叫最后一次): 文件“//frserv bu.playtika.local/users$/constantinio/Documents/Python\u course/Sedinta3/ex.py”,第33行,在 打印(('abc',1,2)>('abc',1,

结果:

print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') )

print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
True
回溯(最近一次呼叫最后一次):
文件“//frserv bu.playtika.local/users$/constantinio/Documents/Python\u course/Sedinta3/ex.py”,第33行,在
打印(('abc',1,2)>('abc',1,'ssst..))
TypeError:“int”和“str”实例之间不支持“>”
进程已完成,退出代码为1

在第一种情况下,
'abc'
'aaa'
之间的比较已经给出了一个结果(
'abc'
在词汇上比
'aaa'
大),因此不执行其余的比较(比较是“短路”)


在第二种情况下,由于所有先前的元素都相等,因此将执行到最后一个元素的比较。
2
'ssst…'
之间的比较失败,但有一个例外,因为前者是
int
类型,后者是
str

类型。第一个比较是将
'abc'
'aaa'
进行比较,然后它知道结果是什么,不必继续到其他元素


在第二次比较中,元组对于前两个元素具有相同的值,因此它必须检查第三个,此时它尝试将
2
'ssst..
进行比较,这会导致您看到的错误。

元组的比较从左侧逐元素进行,直到可以对不相等的值进行比较。就是

True

Traceback (most recent call last):
  File "//frserv-bu.playtika.local/users$/constantinio/Documents/Python_course/Sedinta3/ex.py", line 33, in <module>
    print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1
相当于(带有一些多余的括号)

或者以声明的形式

(a > x) if (a != x) else ((b > y) if (b != y) else (c > z))

在您的示例中,比较
a>x
b>y
有效,但
c>z
无效,因为只能对相同类型的值进行排序。由于仅在必要时进行比较,因此仅当
a==x
b==y
时才会产生错误。实际上,在字符串之间的第一次比较时,比较已经“短路”。字符串在Python中是按字典顺序排列的。@JanChristofterasa你说得对。我没有发现第一个元素也不同。
(a > x) if (a != x) else ((b > y) if (b != y) else (c > z))
# result = (a, b, c) > (x, y, z)
if a != x:
    result = a > x
elif b != y:
    result = b > y
else:
    result = c > z