在Python中按字典的值按降序对其排序,其键按升序对字典进行排序

时间:2019-11-27 04:02:03

标签: python

我的任务是提取字符串中的所有唯一字符(不包括空格),并根据给定字符在字符串中的出现量对其进行排序(因此以降序排列),如果是平局,则按他们的ASCII码。

示例:

  

输入:“我是猫”

     

输出:“ aIcmt”

我特别面临的问题是,如果我使用以下代码进行排序:

char_list = sorted(char_dict.items(), key = lambda x: (x[1],ord(x[0])), reverse = True)

即使我只想对字符出现的值进行排序,它甚至对ord(x[0])进行了反向排序,char对字典的string_list = [char for char in string] string_list = [char for char in string_list if char != ' '] print(string_list) char_dict = {} for char in string_list: if char not in char_dict: char_dict[char] = 0 else: char_dict[char] += 1 char_list = sorted(char_dict.items(), key = lambda x: (x[1],ord(x[0])), reverse = True) print(char_list) for i in char_list: print(i[0], end = '') 部分进行了排序。

这是我的参考代码:

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    if annotation is MGLUserLocation && mapView.userLocation != nil {
        let view = CurrentUserAnnoView(reuseIdentifier: "userLocation")
        self.currentUserAnno = view
        return view
    }
    else if annotation is UserAnnotation{
        let anno = annotation as! UserAnnotation
        let reuseIdentifier = "myCustomAnnotationView"
        if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) {
        // set view properties for current annotation before returing
            annotationView.image = anno.image
            annotationView.name = anno.name // etc.
            return annotationView
        } else {
            let annotationView = UserAnnotationView(reuseIdentifier: reuseIdentifier, size: CGSize(width: 45, height: 45), annotation: annotation)
            annotationView.isUserInteractionEnabled = true
//          anno.view = annotationView // this is strange, not sure if it makes sense
            annotationView.image = anno.image // set annotation view properties
            annotationView.name = anno.name // etc.
            return annotationView
        }
    }
    return MGLAnnotationView(annotation: annotation, reuseIdentifier: "ShouldntBeAssigned")  //Should never happen
}

3 个答案:

答案 0 :(得分:2)

collections.Counter接受一个可迭代的操作(字符串是可迭代的,并且在迭代结束时一次返回每个字符),并将返回一个类似字典的对象,您可以使用该对象从出现的次数对每个条目进行排序most_common

from collections import Counter
counter = Counter(string)
print(''.join(x[0] for x in counter.most_common()))

编辑:

正如疯狂物理学家所说,要排除空间,您可以将生成器传递给Counter

counter = Counter(c for c in string if c != ' ')

答案 1 :(得分:2)

您可以尝试将Countersortedjoin组合使用。

from collections import Counter

input_str = 'I am a cat'

# use counter to get count of each character including white space
t = list(Counter(input_str).most_common())

# sort on count on reverse and ascii on ascending when ties 
t = sorted(t, key=lambda i: (-i[1], i[0])) 

# exclude white space and join remaining sorted characters
res = ''.join(i[0] for i in t if i[0] != ' ') 

print(res)

输出:

aIcmt

答案 2 :(得分:-2)

是否允许您不使用字典来执行此任务?如果是,您可以这样尝试:对每个字母使用计数器,它们检查字符串的字符,不带空格,在匹配的字母上添加一个计数器(使用开关),然后以“”开头的字符串添加具有超过0个计数器的字母(您可以对计数器的int值进行排序以进行排序,也可以在添加字母将到达的位置之前进行检查,排序可能会更容易),之后,您便会拥有所需的内容。 / p>