【问题标题】:how to sort a list in python by two arguments [duplicate]如何通过两个参数对python中的列表进行排序[重复]
【发布时间】:2019-01-17 04:42:22
【问题描述】:

我正在做一个关于手写识别的项目,所以我有图片我必须识别其中的文字所以我所做的是我将图片中的所有字符都设为对象(轮廓),问题是打印后其打印的字符未排序(或按 x 或按 y),我需要的是从左上角到右下角对列表完整对象进行排序。

我尝试按 y 坐标排序,然后按 x 坐标排序,它将从头开始作为 x 坐标排序。

a.sort(key = operator.attrgetter("intRectx"))     
a.sort(key = operator.attrgetter("intRectY"))

我希望项目会按照他们所写的字符打印出来。

class Data():
 num1 = None           
 num2 = None        
 intRectX = 0                # x
 intRectY = 0                # y
 num3 = 0            
 num4 = 0        
 num5 = 0.0             

a = []                                                       # we will fill these shortly
for Data in all:                                    # for all contours
    if Data.checkIfContourIsValid():              # check if valid
        a.append(Data)                            # if so, append to valid contour list
a.sort(key = lambda x: (x.intRectY, x.intRectx))

【问题讨论】:

    标签: python list sorting coordinates


    【解决方案1】:

    使用返回tuplelambda 表达式排序:

    a.sort(key = lambda x: (x.intRectx, x.intRectY))
    

    编辑:

    如果要按 y 排序,则 x 交换顺序:

    a.sort(key = lambda x: (x.intRectY, x.intRectx))
    

    【讨论】:

    • 我已经尝试过了,但我收到错误消息:“TypeError: 'a' object is not subscriptable”
    • @DeanAmir 啊,我犯了一个愚蠢的错误,现在试试
    • 如果您得到AttributeError,请确保intRectxintRectY 是正确的属性
    • 错误消失但仍按X坐标排序
    • @DeanAmir 应该是a.sort(key = lambda x: (x.intRectY, x.intRectx))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多