Home > Blockchain >  Is there any shortcut in python to make a tuple list into a given order?
Is there any shortcut in python to make a tuple list into a given order?

Time:10-04

I am current working on make a tuple list to matrix question, and I am give a tuple list like this [(hello,3),(morning,2),(good,5),(!,1)], and what I need to do for a step is to sort it to a list like [(hello,3),(good,5),(morning,2),(!,1)]. I know how to do it by creating a new list and doing iteration thing, but I am wondering if there are easier thing we can do by python. Like I can sort this by using a list [hello, good, morning,!]. Thank you for helping.

The rule is simply sort the list to a given ordered list.

CodePudding user response:

I say the best way is to construct a dictionary.

Input data:

lst = ['hello', 'good', 'morning', '!']
lot = [('hello', 3), ('morning', 2), ('good', 5), ('!', 1)]

Code:

dct = dict(lot)
print([(i, dct[i]) for i in lst])

Output:

[('hello', 3), ('good', 5), ('morning', 2), ('!', 1)]

This makes the words keys and numbers values of the dictionary, and get's the values in order of the lst.

This is much more efficient than the other answers, since sorted is a pretty massive function.

  • Related