如何首先根据其单位(bit/s、Kbit/s 等)对特定的字典列表进行排序,然后根据它们的值对它们进行排序

Posted

技术标签:

【中文标题】如何首先根据其单位(bit/s、Kbit/s 等)对特定的字典列表进行排序,然后根据它们的值对它们进行排序【英文标题】:How do I sort the particular list of dictionary first on the basis of their Units (bit/s, Kbit/s, etc) and then sort them according to their value 【发布时间】:2021-10-26 05:05:12 【问题描述】:
my_lst = [
        "usage": "0.59 Kbit/s",
        "usage": "383.34 bit/s",
        "usage": "158.13 bit/s",
        "usage": "4.15 Gbit/s",
        "usage": "18.5 Mbit/s",
        "usage": "45 Kbit/s"
    ]

试图实现的输出应该是这样的,带有排序值:-

my_lst = [
    'usage': '4.15 Gbit/s', 
    'usage': '18.5 Mbit/s', 
    'usage': '45 Kbit/s', 
    'usage': '0.59 Kbit/s', 
    'usage': '383.34 bit/s', 
    'usage': '158.13 bit/s'
]

【问题讨论】:

【参考方案1】:

单程使用humanfriendly.parse_size

from humanfriendly import parse_size

sorted(my_lst, key=lambda x: parse_size(x["usage"]), reverse=True)

输出:

['usage': '4.15 Gbit/s',
 'usage': '18.5 Mbit/s',
 'usage': '45 Kbit/s',
 'usage': '0.59 Kbit/s',
 'usage': '383.34 bit/s',
 'usage': '158.13 bit/s']

【讨论】:

【参考方案2】:

您可以使用humanfriendly 模块:

from humanfriendly import parse_size
print(sorted(my_lst, key=lambda x: parse_size(x["usage"])[::-1])

【讨论】:

【参考方案3】:

使用humanfriendly 库的其他答案是更好的解决方案。这只是一种不使用库的替代方法。

from decimal import Decimal

UNIT_MAPPINGS = 
    "": 1,
    "K": pow(10, 3),
    "M": pow(10, 6),
    "G": pow(10, 9),


my_lst = [
    "usage": "0.59 Kbit/s",
    "usage": "383.34 bit/s",
    "usage": "158.13 bit/s",
    "usage": "4.15 Gbit/s",
    "usage": "18.5 Mbit/s",
    "usage": "45 Kbit/s"
]

def convert_rate(rate):
    num, _, unit = rate['usage'].partition(" ")
    unit = unit.replace('bit/s', '')
    return Decimal(num) * UNIT_MAPPINGS[unit]

my_lst.sort(key=convert_rate, reverse=True)
print(my_lst)

输出

['usage': '4.15 Gbit/s', 'usage': '18.5 Mbit/s', 'usage': '45 Kbit/s', 'usage': '0.59 Kbit/s', 'usage': '383.34 bit/s', 'usage': '158.13 bit/s']

【讨论】:

以上是关于如何首先根据其单位(bit/s、Kbit/s 等)对特定的字典列表进行排序,然后根据它们的值对它们进行排序的主要内容,如果未能解决你的问题,请参考以下文章

RFC2544吞吐量测试详细步骤-Renix软件操作演示

蓝牙音频传输格式:SBC ACC APTX LDAC

服务器网络带宽计算

常见的蓝牙耳机音频传输格式都有哪些?

layout需要非常了解清楚的内容

复试问题(通信篇)总结