使用变量作为字典键
问题描述:
在下面的代码中,我试图创建一个循环来检查我的字符串,并将字符串中每个字符的值添加到总变量中。使用变量作为字典键
var stringSent = "babbbababa"
let charValues = ["a":1,"b":2]
var total = 0
for i in stringSent.characters{
switch i{
case "a":
total += charValues["a"]!
//adds 1 to total
case "b":
total += charValues[i]!
//throws error
default:
print("default was sent")
}
print(total)
}
起初,我打算用一个for循环像这样保持线到最少,我很想做,如果我能想出如何让变量“i”正确地被用作关键检索当前字符值。
for i in stringSent.characters {
total += charValues[i]
}
我做错了我的字典或是这种方法不可能吗?我没有发现任何有用的从苹果或谷歌。
答
问题是characters
是字符,但字典中的键是字符串。所以,只是转换:
let stringSent = "babbbababa"
let charValues = ["a":1,"b":2]
var total = 0
for i in stringSent.characters{
total += charValues[String(i)]!
}
或者走另一条路 - 指定在词典的按键应该是性状:
let stringSent = "babbbababa"
let charValues : [Character:Int] = ["a":1,"b":2]
var total = 0
for i in stringSent.characters{
total += charValues[i]!
}
答
看来你要计算在人物的加权总和String
实例stringSent
(给出每个Character
的一些已知权重)。在您自己的实现的问题是,你试图使用从dictionariy的密钥类型不同的变量来访问你的字典键的值(Character
是不一样的String
)
total += charValues[i]! // 'i' is a Character here
您可以简化您的实现并同样避免以多种不同方式使用显式展开(!
),例如施加reduce
到CharacterView
的stringSent
var stringSent = "babbbababa"
let charValues = ["a": 1, "b": 2]
let total = stringSent.characters.reduce(0) { $0 + (charValues[String($1)] ?? 0) }
// 16
(对于此答案的原始误解版本),另一个(稍微更浪费)替代可以是计算在String
实例中的每个字符的频率stringSent
,之后可以将关联权重应用于每个频率以计算总加权和。
var stringSent = "babbbababa"
let charValues = ["a": 1, "b": 2]
var freqs: [String: Int] = [:]
stringSent.characters.forEach { freqs[String($0)] = (freqs[String($0)] ?? 0) + 1 }
print(freqs) // ["b": 6, "a": 4]
let total = freqs.reduce(0) { (sum, kv) in
sum + (charValues[kv.key].map { kv.value*$0 } ?? 0) }
// 16
+1
不熟悉reduce,我会在后面的苹果文档中阅读它。谢谢 – CogHead
谢谢你这么多的这个答案,我有他们在的werent相同的数据类型的感觉,我试图改变字典【性状:INT]“!”但我没有了所以它不会做任何事情。 – CogHead