2 views

edited

I am kind of new to Python. I saw the following code and don't understand how a "list" can be used for sorting a string.

lookup = defaultdict(list)

## Filling the lookup

#  .....

#  .....

inputs = ['abc', 'acb', 'acb'] # a list of strings

result = ''.join(sorted(inputs[0], key=lookup.get))

What I don't understand is the last line the key part. I know it does a lexicographical sort based on the values in the list. I appreciate it if someone can explain it or break this step down to a more readable solution.

For example, if the lookup table looks like this:

{'a' : [-3, 0, 0], 'b': [0, -1, -2], 'c': [0, -2, -1]}

then the result will be this acb

by (36.8k points)
edited by

The key argument to the sorted means "Pretend the value is the result of this function instead of the actual value." So when you sort 'abc' with the lookup table you gave, it does this:

# [1st, 2nd, 3rd] sort order

lookup.get('a') # [ -3,   0,   0]

lookup.get('b') # [  0,  -1,  -2]

lookup.get('c') # [  0,  -2,  -1]

Then it will figure out the sorted order of the above values. Lists are sorted lexicographically meaning the first element is compared first, just like in a dictionary ("aardvark" comes before "beaver" and also before "ant").

After looking at the first elements (-3, 0, 0) we know 'a' has the smallest value, but we don't know which of 'b' and 'c' is smaller. But as soon as we see the second elements (0, -1, -2), we know that 'c' is smaller, so the final order is 'acb' without ever consulting the third elements (0, -2, -1).

Improve your knowledge in data science from scratch using Data science online courses