python - How do I compare 2 lists and order 1 based on the number of matches -


say had list, example:

first_list = ['a', 'b', 'c'] 

and had following list:

second_list = ['a', 'a b c', 'abc zyx', 'ab cc ac'] 

how create function re-orders second list based on total number of times element entire first list matches part of individual string second list?


for further clarity:

  • in second list 'a' string contain 1 match
  • the 'a b c' string contain 3 matches
  • the second example list end in reverse order once function has finished

my attempt:

first_list = ['a', 'b', 'c'] second_list = ['a', 'a b c', 'abc zyx', 'ab cc ac']  print second_list  = 0 keyword in first_list:     matches = 0     s in second_list:         matches += s.count(keyword)         if matches > second_list[0].count(keyword):             popped = second_list.pop(i)             second_list.insert(0, popped)  print second_list 

similar answer:

first_list = ['a', 'b', 'c']     second_list = ['a', 'a b c', 'abc zyx', 'ab cc ac']  #find occurrences list_for_sorting = [] string in second_list:     occurrences = 0     item in first_list:         occurrences += string.count(item)      list_for_sorting.append((occurrences, string))  #sort list sorted_by_occurrence = sorted(list_for_sorting, key=lambda tup: tup[0], reverse=true) final_list = [i[1] in sorted_by_occurrence] print(final_list)  ['ab cc ac', 'a b c', 'abc zyx', 'a'] 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -