python按包含列表的长度对对象列表进行排序

标签 python list sorting object

我有一个包含两个列表的类,一个 int 和一个 string.. 看起来像这样

class Something:
    num = 0

    def __init__(self, clu, pro)
        self.clu = clu
        self.rep = []
        self.rep_dis = []
        self.pro = ""

现在在我的 main 中,我保留了一个 Something 对象的列表。

something_list = []
tmp_something = Something("this", "that")
tmp_something.rep.append("some")
tmp_something.rep_dis.append("thing")
something_list.append(tmp_something)

如何根据对象列表 rep 的长度对该列表进行排序?

编辑:代码段格式

最佳答案

“我如何根据...对对象列表进行排序”的答案总是“使用参数来排序”。在这种情况下:

something_list.sort(key=lambda x: len(x.rep))

key 参数是一个为列表中的每个项目调用的函数,它应该返回您要排序所依据的值。

关于python按包含列表的长度对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25520090/

相关文章:

python - 检查 Windows 应用程序的 "liveness"?

python - 在 Python 中使用 pprint.pprint 后,我​​可以避免排序字典输出吗?

c++ - 返回指向列表中对象的指针

algorithm - 桶排序运行时间

python - 对 numpy 结构化和记录数组进行排序非常慢

python - 如何在正在运行的 doctest 中使用 ipython 的 IPShellEmbed

Python:将内容从一个word文档复制到另一个word文档并保持格式?

python - 如何在Python列表中交换列表中的项目

list - F# If 语句类型不匹配

Android Paging Library - 具有多种排序类型的数据+网络