您将获得存储在变量字符串中的字符串数组。创建一个名为countsStrings的新数组,其中包含type(String,Int)的值。每个元组都包含一个来自strings数组的字符串,后跟一个整数,表示它在strings数组中出现的次数。每个字符串只应在countsStrings数组中出现一次。
我还没有解决问题,因为它已经解决了。我只是想了解它。我可以理解的部分内容和我无法理解的部分内容。我无法理解for循环中的部分。
var a = ["tuples", "are", "awesome", "tuples", "are", "cool","tuples", "tuples", "tuples", "shades"]
var y: [(String,Int)] = []
for z in a{
var x = false
for i in 0..<y.count {
if (y[i].0 == z) {
y[i].1 += 1
x = true
}
}
if x == false {
y.append((z,1))
}
}
print(y)
打印
[(“tuples”,5),(“are”,2),(“awesome”,1),(“cool”,1),(“shades”,1)] cool“,1), (“阴影”,1)]
答案 0 :(得分:2)
如果遇到这样的问题,请先尝试重命名变量。它有助于理解问题。
例如,我拿了你的代码,只是为了清晰起见改变了变量名。现在告诉我是否还有一些你不能得到的东西。
let words = ["tuples", "are", "awesome", "tuples", "are", "cool","tuples", "tuples", "tuples", "shades"]
var tuples: [(String, Int)] = []
for word in words {
var isAlreadyInTupleArray = false
// Loop trough the existing tuples and updates the number of apparition if the word is found
for (index, tuple) in tuples.enumerated() {
let tupleWord:String = tuple.0
let numberOfAppearances:Int = tuple.1
if tupleWord == word {
tuples[index].1 += 1
isAlreadyInTupleArray = true
}
}
// In the case the word was not in the existing tuples, we append a new tuple
if isAlreadyInTupleArray == false {
tuples.append((word, 1))
}
}
print(tuples)
答案 1 :(得分:1)
let arr = ["tuples", "are", "awesome", "tuples", "are", "cool","tuples", "tuples", "tuples", "shades"]
var counts:[String:Int] = [:]
for item in arr {
counts[item] = (counts[item] ?? 0) + 1
}
for (key, value) in counts {
print("\(key) occurs \(value) time(s)")
}