【问题标题】:How can I sort the keys of a dictionary having same values based on the length of the keys?如何根据键的长度对具有相同值的字典的键进行排序?
【发布时间】:2019-04-01 12:20:13
【问题描述】:

给出这样的声明:“印度是一个伟大的国家,我会努力 让我们的国家成为更好的印度”我想订购独特的词 首先是频率,然后是单词的长度,然后是位置 从左边。此语句的输出:国家、印度、朝向、制造、 更好,很好,会,..

我将句子分成单词列表。然后我存储了所有的单词 进入以词频为值的字典,我对 基于降序排列的值的字典。现在我想排序 键(单词)根据它们的长度具有相同的值。那我需要 根据它们的位置对所有具有相同长度的单词进行排序 出现在原句中。

预期输出:国家,印度,朝着,制造,更好,伟大,将……..

s = "India is a great country and I will work towards making our country the better India"  
sen = s.split()  
dictl = {}  
for i in sen:  
    if i in dictl:  
        dictl[i]+=1  
    else:  
        dictl[i]=1  
l = sorted(dictl.items(), key = lambda kv:(kv[1], kv[0]),reverse=True)  
d = dict(l)  
dd = defaultdict(list)  
for k,v in d.items():  
    dd[v].append(k)

【问题讨论】:

  • 请显示您的代码到此为止,否则我们只是将其视为一个根本没有付出任何努力的家庭作业问题
  • 对不起,我是这个论坛的新手,所以无法正确格式化代码

标签: python list dictionary


【解决方案1】:

在这种情况下,您必须创建自己的自定义排序函数,该函数返回(频率、长度、索引)的元组。但是,由于我们使用reverse = True 标志进行排序,我们不需要原始索引,而是拆分单词的长度减去索引,因为这是排序中的最后一个权重。

from operator import itemgetter

first = itemgetter(0)
second = itemgetter(1)

words = s.split()

d = dict()
for word in words:
    if word in d:
        d[word] += 1
    else:
        d[word] = 1

def custom_sort(tup):
    frequency = second(tup)
    length = len(first(tup))
    idx = len(words) - words.index(first(tup))
    return (frequency, length, idx)

sorted(d.items(), key=custom_sort, reverse=True)

[('country', 2),
 ('India', 2),
 ('towards', 1),
 ('making', 1),
 ('better', 1),
 ('great', 1),
 ('will', 1),
 ('work', 1),
 ('and', 1),
 ('our', 1),
 ('the', 1),
 ('is', 1),
 ('a', 1),
 ('I', 1)]

list(map(first, sorted(d.items(), key=custom_sort, reverse=True)))

['country',
 'India',
 'towards',
 'making',
 'better',
 'great',
 'will',
 'work',
 'and',
 'our',
 'the',
 'is',
 'a',
 'I']

【讨论】:

    【解决方案2】:
    //Java Code for Above Problem
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class WordSort2 {
    
        public static void sortWord(String str) {
    
            Map<String, Integer> map = new HashMap<>();
    
            String[] words = str.split(" ");
    
            for (String s : words) {
                int count = 1;
                if (map.containsKey(s)) {
                    map.put(s, map.get(s) + 1);
                } else {
                    map.put(s, count);
                }
            }
            String[] sArray = new String[map.size()];
    
            int count = 0;
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (entry.getValue() > 1) {
                    sArray[count] = entry.getKey();
                    count++;
                }
            }
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (entry.getValue() < 2) {
                    sArray[count] = entry.getKey();
                    count++;
                }
    
            }
    
            sort(sArray);
        }
    
        public static void sort(String[] sArray) {
    
            for (int i = 2; i < sArray.length - 1; i++) {
    
                for (int j = 2; j < sArray.length - i + 1; j++) {
                    if (sArray[j].length() < sArray[j + 1].length()) {
    
                        String temp = sArray[j];
                        sArray[j] = sArray[j + 1];
                        sArray[j + 1] = temp;
                    }
                }
            }
            List<String> list = new ArrayList<>();
    
            for (String s : sArray) {
                list.add(s);
            }
            System.out.println(list);
        }
    
        public static void main(String[] args) {
            sortWord("India is a great country and I will work towards making our country the better India");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多