对元组列表排序。。一张单子。案例不敏感

2024-10-05 12:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我现在看到的是这样一个字符串

hello here, hello there, hello Everywhere

如果有人知道那是什么的话,我正在对kwic进行迭代。所需的格式是元组列表。。排序时不区分大小写。所以最后我有一个未排序的列表

(['here,', 'hello', 'there,', 'hello', 'Everywhere', 'hello'], 0)
(['hello', 'there,', 'hello', 'Everywhere', 'hello', 'here,'], 0)
(['there,', 'hello', 'Everywhere', 'hello', 'here,', 'hello'], 0)
(['hello', 'Everywhere', 'hello', 'here,', 'hello', 'there,'], 0)
(['Everywhere', 'hello', 'here,', 'hello', 'there,', 'hello'], 0)
(['hello', 'here,', 'hello', 'there,', 'hello', 'Everywhere'], 0)`

目前我正在使用类似python的

Final_Array.sort(key = lambda a: a[0][0].lower())

但这给了我一个排序列表

(['Everywhere', 'hello', 'here,', 'hello', 'there,', 'hello'], 0)
(['hello', 'there,', 'hello', 'Everywhere', 'hello', 'here,'], 0)
(['hello', 'Everywhere', 'hello', 'here,', 'hello', 'there,'], 0)
(['hello', 'here,', 'hello', 'there,', 'hello', 'Everywhere'], 0)
(['here,', 'hello', 'there,', 'hello', 'Everywhere', 'hello'], 0)
(['there,', 'hello', 'Everywhere', 'hello', 'here,', 'hello'], 0)`

很明显,hello Everywhere应该在hello there之前,还有hello here。 它的排序是基于将访问列表的第一个单词发送到lower,但是我需要它对访问列表的所有条目进行排序和比较,这样,如果有一个tie,它就会一直比较数组中的下一个值和下一个值,同时忽略大小写。你知道吗


Tags: 字符串hello列表here排序格式sortarray
2条回答
Final_Array.sort(key=lambda x: list(map(str.lower, x[0])))

现在,您的排序只考虑列表中的第一个单词。为了使它能够根据列表中的所有单词按字典顺序排序,排序键应该返回小写单词的列表(输入列表中的每个单词对应一个小写单词)

def sort_key(t):
    word_list, integer = t
    return [word.lower() for word in word_list]

Final_Array.sort(key=sort_key)

由于排序的复杂性,在这种情况下,我希望避免使用lambda,但并非所有人都同意这种观点:-)

相关问题 更多 >

    热门问题