【发布时间】:2014-10-21 16:05:15
【问题描述】:
给定一个Dictionary<String, Arrary<Int>>,在Array<Int> 的第一个5 条目中找出有多少条目具有相同的两个指定值。
例如:
给定:
let numberSeries = [
"20022016": [07,14,36,47,50,02,05],
"13022016": [16,07,32,36,41,07,09],
"27022016": [14,18,19,31,36,04,05],
]
值:7 和 36,结果应该是 2,因为第一个和第二个条目在条目数组的前 5 个条目中同时具有值 7 和 36。
我尝试了很多方法来完成这件事,但我无法让它发挥作用。
这是我目前的尝试:
//created a dictionary with (key, values)
let numberSeries = [
"20022016": [07,14,36,47,50,02,05],
"13022016": [16,07,32,36,41,07,09],
"27022016": [14,18,19,31,36,04,05],
]
var a = 07 //number to look for
var b = 36 // number to look for
// SearchForPairAB // search for pair // Doesn't Work.
var ab = [a,b] // pair to look for
var abPairApearedCount = 0
for (kind, numbers) in numberSeries {
for number in numbers[0...4] {
if number == ab { //err: Cannot invoke '==' with argument listof type Int, @Value [Int]
abPairApearedCount++
}
}
}
这给出了错误:Cannot invoke '==' with argument listof type Int, @Value [Int]就行了:if number == ab
【问题讨论】:
-
对我的意思是值“a”和值“b”在同一个数组、行、前 5 个位置(这就是我使用 [0...4] 的原因)。我把代码分成三部分,前两部分在数组中寻找单个数字,最后一个在同一个数组中寻找两个数字,不知道怎么写。我尝试了不同的东西,但没有做对。我需要它来输出答案“2”,因为数字“a”和“b”一起出现在两条不同的行中。希望这能带来一些启发......
-
好吧,正如@MikeS 所说,目前尚不清楚您要实现什么,但错误很简单 -
ab是一个 Ints 数组,number是一个 Int。它们没有可比性。 -
认为我发送了我过去的评论,就像您发送您的评论一样。希望很清楚,我不想比较这两个值。我想知道它们在同一个数组中出现了多少次。该示例显示了三个数组,但我有数千个。
-
@Francisco 我编辑了你的问题,试图根据你的 cmets 在这里澄清它。如果我遗漏了什么或者我弄错了,请告诉我,我会回滚编辑。
标签: ios arrays dictionary swift