【问题标题】:list populate by append function can't be sorted by sort function通过追加函数填充的列表不能按排序函数排序
【发布时间】:2016-11-27 15:52:16
【问题描述】:

我使用 append 函数创建一个带有循环的列表来填充列表。 在我想使用元素属性之一的列表排序函数对其进行排序之后。但它不起作用,你们能帮帮我吗,非常感谢。 这是代码

def processRawUrlData():
    rawData = readHtml()
    taskList = []
    for item in rawData:
        if item != '':
            taskList.append(processTask(item))
    taskList.sort(key=attrgetter('est_time'))
    for item in taskList:
        print(item.taskname)
        print(item.est_time)
        print(item.submittedDate)
    return taskList

【问题讨论】:

  • “它不起作用”是什么意思?你有例外吗?您的列表是否根本没有排序,或者它是否已排序,但不是您想要的方式?这些事情我们猜不透!您可能还想显示processTask 返回值的est_time 属性是什么样的,因为这是您尝试排序的依据。
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误和在问题本身中重现它所需的最短代码。没有明确的问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable Example。
  • 当我说它不起作用时,这意味着列表根本没有排序。

标签: python list sorting


【解决方案1】:

我认为您可能必须更具体并提供比较功能,以便您的列表可以排序。从以下站点获取以下代码。希望对您有所帮助:

https://wiki.python.org/moin/HowTo/Sorting

    >>> student_tuples = [
            ('john', 'A', 15),
            ('jane', 'B', 12),
            ('dave', 'B', 10),
    ]
    >>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 2022-10-23
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2011-05-21
    • 1970-01-01
    相关资源
    最近更新 更多