Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 根据值对字典排序并提取相应的键_Ios_Swift - Fatal编程技术网

Ios 根据值对字典排序并提取相应的键

Ios 根据值对字典排序并提取相应的键,ios,swift,Ios,Swift,我有一个Swift中的字典数据结构,带有键、值对,我想根据值按降序对字典排序,然后得到前3个值对应的前3个键 例如: 排序前: Dictionary<'A', 8> Dictionary<'B', 23> Dictionary<'C', 56> Dictionary<'D', 3> Dictionary<'E', 9> Dictionary<'F', 20> 字典 字典 字典 字典 字典 字典 排序后: Diction

我有一个Swift中的字典数据结构,带有键、值对,我想根据值按降序对字典排序,然后得到前3个值对应的前3个键

例如:

排序前:

Dictionary<'A', 8>
Dictionary<'B', 23>
Dictionary<'C', 56>
Dictionary<'D', 3>
Dictionary<'E', 9>
Dictionary<'F', 20>
字典
字典
字典
字典
字典
字典
排序后:

 Dictionary<'C', 56>
 Dictionary<'B', 23>
 Dictionary<'F', 20>
 Dictionary<'E', 9>
 Dictionary<'A', 8>
 Dictionary<'D', 3>
字典
字典
字典
字典
字典
字典
所以我需要C,B和A

(数组(arr)中的(键,值)。排序{$0.1<$1.1}){
for (key,value) in (Array(arr).sorted {$0.1 < $1.1}) {
    println("\(key):\(value)")
}
println(“\(键):\(值)”) }
要获取与字典排序值关联的前三个键,(1)按其值对数组进行排序,(2)从排序后的数组中按顺序获取键,然后(3)从该数组中取出前三个键:

let dict = ["A":8, "B":23, "C":56, "D":3, "E":9, "F":20]

// Sort the dictionary by its values
let sortedArray = sorted(dict, {$0.1 > $1.1})

// Get an array of the keys from the sorted array
let keys = sortedArray.map {return $0.0 }

// Get the first three keys
let firstThreeKeys = keys[0..<3]
println(firstThreeKeys)
让dict=[“A”:8,“B”:23,“C”:56,“D”:3,“E”:9,“F”:20]
//按其值对词典进行排序
让sortedArray=sorted(dict,{$0.1>$1.1})
//从排序的数组中获取一个键数组
let keys=sortedArray.map{return$0.0}
//拿到前三把钥匙

让firstThreeKeys=keys[0..在Swift 2中,您可以执行以下操作,例如:

let dict = ["A":8, "B":23, "C":56, "D":3, "E":9, "F":20]

let sa = dict.sort({$0.1 > $1.1}).prefix(3).map { $0.0 } // ["C", "B", "F"]

你的意思是你想要C,B和F吗?对不起,是的,我是说C,B和F,谢谢你指出这一点…谢谢大家的答案!任何答案对你有用吗?这只是问题的一半。OP想要前三个键,顺序。非常酷!但这返回的是值而不是键,即[56,23,20]