我正在尝试获取数组字典中的最大值,我还需要获取该数组的键。
这就是我得到最大值的方式:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
答案 0 :(得分:1)
你可以使用Swift功能。
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
if let value = interestingNumbers.map ({ ($0, $1.max() ?? 0) }).max(by: { $0.1 < $1.1 }) {
print(value.0, value.1) // Square 25
}
让我们一步一步走
首先,我创建了tuple
类型为[(String, Int)]
的数组,第一个位置它将存储组,第二个位置它将存储相应数组的最大值。
let array = interestingNumbers.map ({ ($0, $1.max() ?? 0) })
//[("Fibonacci", 8), ("Square", 25), ("Prime", 13)]
现在从元组数组中找到最大Int
。
if let value = array.max(by: { $0.1 < $1.1 }) {
print(value.0, value.1) //Will print group here it is "Square 25"
}
答案 1 :(得分:1)
我会在字典值中使用max方法,并从生成的元组值中获取最大值:
if let result = interestingNumbers.max(by: {$0.value.max() ?? 0 < $1.value.max() ?? 0}),
let maxValue = result.value.max() {
print(result.key) // "Square\n"
print(result.value) // "[1, 4, 9, 16, 25]\n"
print(maxValue) // 25
}
答案 2 :(得分:0)
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var largest_kind : String? =nil
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largest_kind = kind
}
}
}
答案 3 :(得分:0)
为什么不使用元组来保持最大值?
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest: (kind: String?, number: Int) = (nil, 0)
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest.number {
largest = (kind, number)
}
}
}
可以进一步简化为:
var largest: (kind: String?, number: Int) = (nil, 0)
for (kind, numbers) in interestingNumbers {
let max = numbers.max() ?? 0
if max > largest.number {
largest = (kind, max)
}
}
另一种方法是首先将值展平为(kind, number)
序列:
let flattened = interestingNumbers
.map { (kind, numbers) in numbers.map { (kind, $0) } }
.joined()
let largest = flattened.max(by: { $0.1 < $1.1} )
print(largest)
或者您可以意识到只有每个数组中的最大值才是最重要的,因此:
let largestPerKind = interestingNumbers
.map { (kind, numbers) in (kind, numbers.max() ?? 0) }
let largest = largestPerKind.max(by: { $0.1 < $1.1} )
print(largest)