如何在Dart中按列表的降序对列表中的项目进行排序?

时间:2020-08-10 10:05:07

标签: list dart

假设我有列表l=[a,b,c,d,a,s,b,d,c,r,s,r,r,s,w,c,r]

所以a = 2,b = 2,c = 3,d = 2,s = 3,r = 4,w = 1的发生次数

因此最终结果应为列表l=[r,s,c,a,b,d,w]

因为r被重复了很多次, 重复s的次数最多,但少于r,依此类推。应该按频率降序

2 个答案:

答案 0 :(得分:2)

好吧,如果您想使用一种紧凑的方式来执行此操作,则可以使用以下代码:

void main() {
  final input = ['a', 'b', 'c', 'd', 'a', 's', 'b', 'd', 'c', 'r', 's', 'r', 'r', 's', 'w', 'c', 'r'];
  print(itemsByFrequency(input)); // [r, c, s, a, b, d, w]
}

List<String> itemsByFrequency(List<String> input) => [
      ...(input
              .fold<Map<String, int>>(
                  <String, int>{},
                  (map, letter) => map
                    ..update(letter, (value) => value + 1, ifAbsent: () => 1))
              .entries
              .toList()
                ..sort((e1, e2) => e2.value.compareTo(e1.value)))
          .map((e) => e.key)
    ];

答案 1 :(得分:0)

使用collection模块在​​地图中进行排序

import 'dart:collection';

void main() {
  List<String> l=['a','b','c','d','a','s','b','d','c','r','s','r','r','s','w','c','r'];
  
  //maintaing the map to keep the count of the item
  Map item = {};
  
  // adding the count of the item
  l.forEach((e){
    // if item key is there, then +1
    if(item.containsKey(e)) item[e] += 1;
    else item[e] = 1;
  });
  
  // sorting the item based on decreasing order
  var sortedKeys = item.keys.toList(growable:false)
    ..sort((k1, k2) => item[k2].compareTo(item[k1]));
  LinkedHashMap sortedMap = new LinkedHashMap
      .fromIterable(sortedKeys, key: (k) => k, value: (k) => item[k]);
  
  // this will contain the keys from sortedMap
  List myList = [];
  sortedMap.forEach((k,v){
    myList.add(k);
  });
  
  print(myList);
}

输出

[r, c, s, a, b, d, w]