Home > Back-end >  python: Simplest way to sort a list by a calculated value
python: Simplest way to sort a list by a calculated value

Time:02-24

If I have a master_list (list of lists), I want to know what the simplest way would to sort it by x value (I'll call it score). Score (a float) is derived by calling a function that calculates it based on the items in master_list[i] (a list).

The way I was going about is like this:

for i in range(len(master_list):
  # call get_score(master_list[i]) (function that calculates score for master_list[i]) and 
  insert to index 0 in master_list[i]
sorted_list = sorted(master_list)
for i in range(len(master_list):
  master_list[i].pop(0)

My function get_score() returns the a single float for one of the lists in master_list

It is important not to modify the original master_list, hence why I am removing score from master_list[i]. What I wish to know is if there is any way to accomplish without adding score to each master_list[i], then removing it.

I also tried something like this but I don't believe it would work:

score_sorted = sorted(master_list, key=get_score(iterm for item in master_list))

Expected output: master_list = [['b', 1]['a', 2]['c', 3]] If the score for master_list[i] are 3, 2, 1 for all items respectively then the ouput would be: master_list_with_score = [[3,'b', 1][2,'a', 2][1,'c', 3]] sorted_by_score_master_list = [['c', 3]['a', 2]['b', 1]]

Sorry about the formatting, it's my first time posting. Let me know if there is need for any clarification

CodePudding user response:

sorted(master_list, key=get_score)

CodePudding user response:

I would keep a seperate list of scores.

master_list = master_list
score = get_score(master_list[i]) # i am assuming it returns a list of scores for the same index in master list
sorted(zip(score, master_list)) # then master list is sorted by the scores

If you want a seperated sorted list,

sorted_master_list = [i for (score,i) in sorted(zip(score, master_list))]
  • Related