Dringo
Dringo

Reputation: 265

Sort a List of a Tuple.. of a list. Case insensitive

So what I have currently is a string that looks like this,

hello here, hello there, hello Everywhere

I'm making a iteration of kwic if anyone knows what that is. The format that is required is a list of tuples.. of list while sorting case insensitive. So in the end I have a unsorted list that looks like

(['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)`

Currently I am using a python sort like

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

But that gives me a sorted list that looks like

(['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)`

Obviously the hello Everywhere should be before the hello there, along with hello here. It's sorting based on sending the first word of the accessed list to lower, but I need it to sort and compare all entries of the accessed list so that there if there is a tie it just keeps comparing the next value in the array and the next, all while ignoring case.

Upvotes: 0

Views: 194

Answers (2)

mgilson
mgilson

Reputation: 310099

Right now, your sort is only taking into account the first word in the list. In order to make it sort lexicographically based on all the words in the list, your sort key should return a list of lower-cased words (one lower-cased word for each word in the input list)

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

Final_Array.sort(key=sort_key)

Due to the complexity of the sort, I'd prefer to avoid the lambda in this case, but not everyone necessarily agrees with that opinion :-)

Upvotes: 2

Patrick Haugh
Patrick Haugh

Reputation: 61042

Final_Array.sort(key=lambda x: list(map(str.lower, x[0])))

Upvotes: -1

Related Questions