gpt4 book ai didi

dart - 如何对 map 的值进行排序?

转载 作者:行者123 更新时间:2023-12-04 19:36:14 31 4
gpt4 key购买 nike

有人可以给我一个提示吗?我想按列表的长度对 map 的值进行排序。

var chordtypes = {
"maj": [0, 4, 7],
"M7": [0, 4, 7, 11],
"m7": [0, 3, 7, 10],
"6": [0, 4, 7, 9],
"9": [0, 4, 7, 10, 14],
"sus2": [0, 2, 7],
"sus4": [0, 5, 7],
"omit3": [0, 7],
"#5": [0, 4, 8],
"+7b9#11": [0, 4, 8, 10, 13, 18],
"+9": [0, 4, 8, 10, 14]
};

最佳答案

一个按长度对列表映射进行排序的函数。

import 'dart:collection';

/// sorts the ListMap (== A Map of List<V>) on the length
/// of the List values.
LinkedHashMap sortListMap(LinkedHashMap map) {
List mapKeys = map.keys.toList(growable : false);
mapKeys.sort((k1, k2) => map[k1].length - map[k2].length);
LinkedHashMap resMap = new LinkedHashMap();
mapKeys.forEach((k1) { resMap[k1] = map[k1] ; }) ;
return resMap;
}

结果为:
var res = sortListMap(chordtypes);
print(res);

==>
{ omit3: [0, 7], 
maj: [0, 4, 7],
sus2: [0, 2, 7],
sus4: [0, 5, 7],
#5: [0, 4, 8],
M7: [0, 4, 7, 11],
m7: [0, 3, 7, 10],
6: [0, 4, 7, 9],
9: [0, 4, 7, 10, 14],
+9: [0, 4, 8, 10, 14],
+7b9#11: [0, 4, 8, 10, 13, 18] }

关于dart - 如何对 map 的值进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29628713/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com