Reputation: 51
I need to sort my list in alphabetical order but ignore the case of my letters.
my_list = [('CAT', 1), ('Crop', 1), ('PoP', 4), ('anTs', 1), ('apple', 1), ('cAt', 1), ('can', 1), ('dog', 1), ('long', 1), ('poeT', 1), ('toe', 2)]
I would like to receive :
my_list_sorted = [('anTs', 1), ('apple', 1), ('can', 1), ('CAT', 1), ('cAt', 1), ('Crop', 1), ('dog', 1), ('long', 1), ('poeT', 1), ('PoP', 4), ('toe', 2)]
I tried to do :
sorted(set(my_list),key=str.lower())
But I received this error :
TypeError: descriptor 'lower' of 'str' object needs an argument
Someone can help me please ?
Thank you, Jason
Upvotes: 2
Views: 1234
Reputation: 218
If you don't need to keep an original version of the list it's quicker to sort in place by calling a list method:
my_list.sort(key=lambda tup: tup[0].lower())
this method doesn't return anything because the original list object now becomes sorted.
Upvotes: 2
Reputation: 1140
This should work:
sorted(my_list, key=lambda x: x[0].casefold())
The key
parameter of the function sorted
is the value that will be used for comparison in the sorting process. In this case the key
we want is the string part of the tuples in lowercase, so that's what we return using a one-line lambda function.
In python str
is a basic built in function that converts the value passed to a string, that's why the error.
See str.casefold()
to understand why is prefered over str.lower()
Upvotes: 8
Reputation: 2127
You need to provide a key function:
sorted(my_list, key=lambda item : item[0].lower())
Upvotes: 0