Python对象列表排序失败求助:按points类end属性排序异常
问题分析与解决方案
你的问题出在输入数据的类型处理上!
看一下你的代码片段:
a,b=input().split() l.append(points(a,b))
input().split()默认返回的是字符串类型的值,所以你的points对象的begin和end属性实际上都是字符串。而字符串的排序规则和数字完全不同:比如字符串 "11" 和 "8" 比较时,会先对比第一个字符的ASCII码,'1' 比 '8' 小,所以 "11" 会被判定为小于 "8",这就是导致排序结果和预期不符的核心原因。
修复方案
只需要在读取输入时,把字符串转换成整数即可,修改这一行代码:
a,b = map(int, input().split())
这样points对象的end属性就会存储整数类型的值,使用sorted(l, key=lambda obj: obj.end)排序时,就会按照数字的大小逻辑来排列,得到你想要的结果。
修改后的完整代码
class points: def __init__(self,a,b): self.begin=a self.end=b t=int(input()) while t: t-=1 l=[] index=[] n=int(input()) for i in range(n): # 将输入的字符串转换为整数 a,b = map(int, input().split()) l.append(points(a,b)) l=sorted(l, key=lambda obj: obj.end) for i in range(n): print(l[i].begin,l[i].end)
验证结果
输入:
1 3 5 8 9 12 6 11
输出:
5 8 6 11 9 12
完全符合你的预期。
内容的提问来源于stack exchange,提问作者Naman Anand
相关产品推荐
相关产品推荐

