【问题标题】:Python sort() with lambda key - list of nums vs chars带有 lambda 键的 Python sort() - nums 与 chars 的列表
【发布时间】:2021-09-14 02:12:52
【问题描述】:

我正在尝试将按每个数字的频率对数字列表进行排序的解决方案应用于字符列表。

我对数字进行排序的解决方案是:

def num_sort_by_freq(list_of_nums):

    num_count = {}

    for num in list_of_nums:
        if num not in num_count:
            num_count[num] = 1
        else:
            num_count[num] += 1

    list_of_nums.sort(key = lambda x:num_count[x])

    return list_of_nums

print(num_sort_by_freq([1,1,1,2,2,2,2,3,3,3]))

输出:[1, 1, 1, 3, 3, 3, 2, 2, 2, 2]

尝试对字符进行排序:

def char_sort_by_freq(string_to_be_list):

    list_of_chars = list(string_to_be_list)

    char_count = {}

    for char in list_of_chars:
        if char not in char_count:
            char_count[char] = 1
        else:
            char_count[char] += 1

    list_of_chars.sort(key = lambda x:char_count[x])

    return "".join(list_of_chars)

print(char_sort_by_freq("asdfasdfasdddffffff"))

输出:asasasddddddffffffff

预期输出:aaasssddddddffffffff

我已经经历了太多次,无法理解为什么输出的 'a's 和 's's 是混杂在一起的,而不是顺序的。

感谢任何帮助。

编辑:非常感谢您的帮助! Lambda 函数对我来说是新领域。

【问题讨论】:

  • 你的字符串有相同数量的as,所以sort 只是按照它找到它们的顺序保留它们:交替

标签: python python-3.x list lambda


【解决方案1】:

您可以将key 函数更改为返回tuple 来处理平局:

def char_sort_by_freq(string_to_be_list):

    list_of_chars = list(string_to_be_list)

    char_count = {}

    for char in list_of_chars:
        if char not in char_count:
            char_count[char] = 1
        else:
            char_count[char] += 1

    list_of_chars.sort(key = lambda x:(char_count[x], x))
    #                                  ^^^^^^^^^^^^^^^^^
    return "".join(list_of_chars)

print(char_sort_by_freq("asdfasdfasdddffffff"))

输出:

aaasssdddddffffffff

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多