【问题标题】:Pythonic way to sort array of string by an associated numberPythonic按关联数字对字符串数组进行排序的方法
【发布时间】:2016-08-09 13:18:33
【问题描述】:

需要对 HOST 字符串数组按其关联的浮动速度进行排序

有没有从排序的元组中获取数组的好方法? 我可以消除有序数组吗?

#!/usr/bin/env python

def getSpeed(url):
    if url == 'h1':
         return 0.522611856461
     elif url == 'h2':
         return 0.438368797302
     elif url == 'h3':
         return 0.443703174591

def orderHosts():
    hostInfo = []
    ordered = []
    hosts = ['h1', 'h2', 'h3']
    for host in hosts:
        hostInfo.append( (host, getSpeed(host)) )

    print hostInfo
    return ordered

if __name__ == "__main__":
    print("orderedHosts {}".format(orderHosts()))

输出:

[('h1', 0.522611856461), ('h2', 0.438368797302), ('h3', 0.443703174591)]

orderedHosts []

【问题讨论】:

  • 为什么你有一个函数来存储值?为什么不使用dictionary?你到底想做什么?
  • 函数 orderedHosts 需要返回按 getSpeed 值排序的主机数组。 hostInfo 可以是字典而不是数组,我在其中添加元组,所以 append 会变成 hostInfo[speed] = host。我认为对元组进行排序会更容易。
  • 你误解了我的意思。我说的是getSpeed函数
  • 在我的实际软件程序(用于支票兑现)中,getSpeed 小函数是一系列精心制作的 XML 文档请求,通过请求响应——会让你的头发卷曲。我只需要排序提示。

标签: python sorting dictionary tuples


【解决方案1】:

可以使用sortsortedkey参数设置排序前调用的函数。在你的情况下,sorted(hosts, key=getSpeed) 应该足够了。

【讨论】:

    【解决方案2】:

    sorted 内置函数接受 key= 参数。您可以使用它来提供一个返回比较键(在本例中为速度)的函数,如下所示:

    def getSpeed(host):
        ... as you had it
        return speed
    
    hosts = ['h1', 'h2', 'h3']
    ordered_hosts = sorted(hosts, key=getSpeed)
    

    【讨论】:

    • 在我的实际程序中,getSpeed 函数从 Requests 返回一个 Response 对象,该对象是一个 XML 文档,可能存在错误状态等。有一个 Response.duration 属性,但没有像 getSpeed 这样的简单函数。我想尝试询问有关对元组数组进行排序,将元组转换为数组或对字典进行排序,将字典转换为数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多