我试图检查一个条件是否为真,其中所有的部分都是整数,我没有使用任何'<‘符号,但我仍然得到了这个错误。我真的很困惑..。
代码:
import sys
packets, packets_x, packets_y, packets_z = [], [], [], []
for packet in sys.stdin:
if packet == "\n":
break
packets.append(packet[:-1])
packets_x.append(int(list(packet.split())[0]))
packets_y.append(int(list(packet.split())[1]))
packets_z.append(int(list(packet.split())[2]))
while True:
for number in range(len(packets)):
if int(sorted(packets_x)[0]) == packets_x[number] and int(sorted(packets_y)[0]) == packets_y[number] and int(sorted(packets_z)[0]) == packets_z[number]:
print(packets[number])
packets[number] = "a"
packets_x[number] = "a"
packets_y[number] = "a"
packets_y[number] = "a"
if packets.count("a") == len(packets) + 1:
break我所用的投入:
6220 1 10 Because he's the hero Gotham deserves,
6210 1 10 Asd
<ENTER><ENTER> --点击enter,不要实际键入.逐行键入输入,不要一次全部输入。
我得到的错误:
if int(sorted(packets_x)[0]) == packets_x[number] and int(sorted(packets_y)[0]) == packets_y[number] and int(sorted(packets_z)[0]) == packets_z[number]:
TypeError: '<' not supported between instances of 'str' and 'int'这可能是某种Python错误吗?
发布于 2017-09-26 18:57:28
if语句不使用“<”符号,但sorted()函数使用!
我得到了错误,因为sorted()函数不能对不同类型的变量进行排序。
如果我们尝试sorted([1, "a string"]),您将得到错误,但如果我们尝试sorted([5, 2]),它将工作。
这个解决方案是根据马克·狄金森和巴玛尔的评论写成的。
发布于 2020-05-01 17:15:44
问题似乎出现在Python3中,而不是Python2.7中,python3的解决方案可以是:
>>> a = [1,2,3,'bla',4,5,None]Python2.7 2.7:
>>> sorted(a)
[None, 1, 2, 3, 4, 'bla']Python3:
>>> sorted(a)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'可通过以下方式固定:
>>> sorted(a, key=lambda x: str(x))
[1, 2, 3, 4, 5, None, 'bla']https://stackoverflow.com/questions/46433451
复制相似问题