我有格式词典
myDict: Dictionary <String, Dictionary>
例如,
“AUTOID-1” {
“key1” : “val1_1”,
“key2” : “val2_1:
},
“AUTOID-2” {
“key1” : “val1_2”,
“key2” : “val2_2:
},
“AUTOID-3” {
“key1” : “val1_3”,
“key2” : “val2_3:
}
对于整个数据集,我想找出最高和最高值 key2 AUTOID 的值强>
使用
myKeyData = myDict.allKeys
我可以获得所有 AUTOID 的数组,然后我可以使用以下内容进行进一步处理:
for index in 0...myKeyData.count-1 {
if let insideDict = myDict[myKeyData[index]] as? NSDictionary {
// FURTHER PROCESSING
}
}
是否有更好的方法来实现找到与 key2 的最高和最低值相对应的 AUTOID 的目标
答案 0 :(得分:1)
我会使用map
来获取包含键("AUTOID-N"
)和值("valX_Y"
)的元组数组,然后获取min
和{{1}根据仅比较值的比较器来计算该数组。
max
答案 1 :(得分:0)
使用reduce
:
let myDict = ["AUTOID-1": ["key1" : "val1_1", "key2" : "val2_1"],
"AUTOID-2": ["key1" : "val1_2", "key2" : "val2_2"],
"AUTOID-3": ["key1" : "val1_3", "key2" : "val2_3"]]
let initalElement = (min: myDict.first!, max: myDict.first!)
let result = myDict.reduce(initalElement) { (aggregate, element) in
guard let minValue = aggregate.min.value["key2"],
let maxValue = aggregate.max.value["key2"],
let currentValue = element.value["key2"] else {
return aggregate
}
let newMin = currentValue < minValue ? element : aggregate.min
let newMax = currentValue > maxValue ? element : aggregate.max
return (min: newMin, max: newMax)
}
print(result.min)
print(result.max)
这假设myDict
非空。您基本上选择myDict
的第一个元素来启动reduce
循环,并将其与myDict
中其余的键值对进行比较。