【问题标题】:python: how to sort a list of letters and numberspython:如何对字母和数字列表进行排序
【发布时间】:2018-09-03 17:03:36
【问题描述】:

lista = [300KB, 12MB, 100KB, 1GB],我要处理lista,然后改成[100KB, 300KB, 12MB, 1GB]

如何使用简单的方法对其进行排序?

【问题讨论】:

    标签: python list sorting numbers letters


    【解决方案1】:

    "lista" 必须是字符串列表。 sorted 是你的朋友。 Sorting Mini-HOW TO

    def memory_mult(text):
        memory = {'KB':1024, 'MB':1024**2, 'GB':1024**3}
        num = text[:-2]
        mult = text[-2:]
        return int(num)*memory[mult]
    
    sorted(lista, key=memory_mult)
    

    【讨论】:

    • 非常感谢!这是我看到的最简单的方法。
    • 使用float(num) 代替int(num) 可能是健壮的。
    猜你喜欢
    • 2018-04-09
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多