简体   繁体   English

按字典 python 的值对列表进行排序

[英]Sort a list by value of a dict python

I need some help, how to use the algorithm selection sort to sort a list by the values of a dict.我需要一些帮助,如何使用算法选择排序按字典的值对列表进行排序。 I wrote some code but I don't know how continue, that the code work.我写了一些代码,但我不知道如何继续,代码工作。

months = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}

L = ["March", "January", "December"]

eg sort the list by the values of the dict例如,按字典的值对列表进行排序

def month(L):
    for i in months:
       minpos = i
       for j in range (months[i], len(L)):
           if months[L[j]] > months[minpos]:
             months[minpos] = months[L[j]]

       L[j], L[minpos] = L[minpos], L[i] 

return L

Your code:你的代码:

months = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}
L = ["March", "January", "December"]

Convert month name(str) in L to corresponding number, then sort it.将L中的月份名称(str)转换为对应的数字,然后排序。

num_L = sorted( [months[month] for month in L] )

Convert sorted number to corresponding month name.将排序后的数字转换为相应的月份名称。

res = [k for number in num_L for k,v in months.items() if number == v]

Maybe you need some string operations just like uppercase() or lower() before matching month name.在匹配月份名称之前,您可能需要一些字符串操作,例如大写()或小写()。

New Answer新答案

  • Create class selection_sort which has get_sorted() method that will sort the list based on dictionary values using selection sort.创建 class selection_sort它具有get_sorted()方法,该方法将使用选择排序根据字典值对列表进行排序。
  • Here we compare two value and if first value is greater than second, than swap both the values.在这里,我们比较两个值,如果第一个值大于第二个值,则交换两个值。 Repeat this step until entire list is sorted.重复此步骤,直到对整个列表进行排序。

class selection_sort:
    """Sort the list based on dictionary value using selection sort."""
    def __init__(self,L):
        self.months = {"January": 1, "February": 2, "March": 3, "April": 4,
                   "May": 5,
                  "June": 6, "July": 7, "August": 8, "September": 9,
                  "October": 10, "November": 11, "December": 12}
        self.L = L

    def get_sorted(self):
        """ sorting list."""
        month_num =  [self.months[i] for i in self.L]
        flag = True  # set Flag is True to enter the loop.
        while flag:
            flag = False  # set Flag to False for no swaping done

            for i in range(len(month_num)-1):
                if month_num[i] > month_num[i+1]:
                    flag = True  # set Flag to False if no swaping is done
                    # swap
                    month_num[i], month_num[i+1] = month_num[i+1], month_num[i]

        L = [k for k, v in self.months.items() if v in month_num]
        print(L)
        return L

Test Case测试用例

  • Test which you have written is comparing L with Expected .您编写的测试是将LExpected进行比较。 It should compare actual with expected .它应该将actualexpected进行比较。 self.assertEqual(L, expected)

  • Also, expected = ["March", "May", "December", "October", "September"] is incorrect.此外,expected = ["March", "May", "December", "October", "September"]不正确。 It should have been ["March", "May","September", "October", "December"]应该是["March", "May","September", "October", "December"]

import unittest
from selectionSort import selection_sort

# @unittest.skip("")
class TestInPlace(unittest.TestCase):
    def test_1(self):
        L = ["December", "September", "March", "October", "May"]
        obj = selection_sort(L)
        actual = obj.get_sorted()
        expected = ["March", "May","September", "October", "December"]
        self.assertEqual(actual, expected)

Old Answer旧答案

Try this,尝试这个,

#creating list L1
L1 = [months[L[i]] for i in range(len(L))]
print(L1)

#sorting list using algorithm selection sort
for i in range(1,len(L1)):
    j = 0
    if L1[j] > L1[i] :
        L1[j], L1[i] = L1[i] ,L1[j]
print(L1)

#Replacing values with key
sorted_list = [ k   for k,v  in months.items() for i in L1 if i == v]
print(sorted_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM