3

I have the following code:

v = ['zack', 'timor', 'Topher']
v.sort()
print(v)

['Topher', 'timor', 'zack']

What I want to get is:

['timor','Topher', 'zack']

which is the correct alphabetic order.

Basically it should ignore the difference between lower and upper letters. I can't just do lower() because ['timor','topher', 'zack'] is not the desired output.

in simple words I want it to compare with this rule: a=A, b=B, ... How can I do that?

HaloKu
  • 405
  • 2
  • 7
  • 17
  • you can do a more complicated map function where essentially you remember which words got changed, sort them and change them back. You can do this with a fairly naively in python using a 2d array and sorting both arrays. I can write an answer if you would like – gnahum May 09 '20 at 21:21

3 Answers3

8

Okay, so the sort function allows you to specify a key with which to compare elements;

v.sort(key=str.lower)

Source: https://docs.python.org/3/howto/sorting.html

cadolphs
  • 9,014
  • 1
  • 24
  • 41
4

You can specify a key function for sort. This would do it for this data:

v = ['zack', 'timor', 'Topher', 'Quark', "quark"]
v.sort( key= lambda x: x.lower())
print(v)

v = ['zack', 'timor', 'Topher', 'Quark', "quark"]
v.sort( key= lambda x: (x.lower(), x[0].isupper()))  # this will sort lower before upper
print(v)

['Quark', 'quark', 'timor', 'Topher', 'zack']  # keep original order
['quark', 'Quark', 'timor', 'Topher', 'zack']  # always lower before upper, only 1st char

But v.sort( key= lambda x: x.lower()) will stable sort - meaning it sorts by lowercasing and keeps the occurence order of the original list.

See

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

Add a key to your sorting, like:

def case_insensitive_sort(a):
    return a.lower()

v = ['zack', 'timor', 'Topher']
v.sort(key=case_insensitive_sort)
print(v)
Anis R.
  • 6,656
  • 2
  • 15
  • 37