Dan
Dan

Reputation: 39

How would you order a list containing lists using another list containing lists?

So, I coded a quick Python program to create Huffman trees based on a text file. So far, everything is great, except for the way I present the resulting huffman codes. To follow convention, I wish to display them from the most frequent to the least frequent. Luckily, I have another list that stores the frequency and corresponding letter. This frequency list is already sorted. My issue is I don't know what key to use to sort the second list using the values from the first list.

frequencies = [[6, 's'], [4, 'e'], [4, 'l'], [3, ' '], [2, 'h'], [1, 'a']]
huffman_codes = [['s', '10'], ['h', '011'], ['e', '111'], [' ', '101'], ['l', '00'], ['a', '001']]

What I want is

[['s', '10'], ['e', '111'], ['l', '00'], [' ', '101'], ['h', '011'], ['a', '001']] 

Because Huffman codes with high frequency have the shortest length codes, I tried sorting them through their code length, but this isn't necessarily true, since my program allows the user to change whether they should start with a 1 or 0 on the left. Why the codes get unsorted is the nature of drawing the huffman tree.

Upvotes: 1

Views: 73

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use a lookup dictionary to get the key:

frequencies = [[6, 's'], [4, 'e'], [4, 'l'], [3, ' '], [2, 'h'], [1, 'a']]
huffman_codes = [['s', '10'], ['h', '011'], ['e', '111'], [' ', '101'], ['l', '00'], ['a', '001']]

lookup = {y : x for x, y in frequencies}
result = sorted(huffman_codes, key=lambda x: lookup[x[0]], reverse=True)

print(result)

Output

[['s', '10'], ['e', '111'], ['l', '00'], [' ', '101'], ['h', '011'], ['a', '001']]

Upvotes: 6

Related Questions