gpt4 book ai didi

javascript - 将字典值中的整数分配给字符串的字符

转载 作者:行者123 更新时间:2023-11-28 07:55:05 24 4
gpt4 key购买 nike

indicesfor value in 很好地为我提供了我正在寻找的循环,但是我需要更进一步并将字典的值分配给匹配项然后对字符串的字符进行得分计算。

我想知道完成此任务的最快捷方式。这可能使用 map 吗? 让 curChar = n.map({ print($0) })

另一个问题是 Javascript 让您可以轻松地使用异构类型字典,但对于 Swift,我们需要匹配类型。

var dict: [String:Any] = ["a":1, "j":1, "s":1, "b":2, "k":2,"r":9/*...*/]

let n = "lighthouse"
var nScore = 0

for i in n.indices[n.startIndex..<n.endIndex] {
let curChar = n[i]
var curVal = dict[curChar]
nScore = nScore + curVal

原始的 Javascript block 。

var dict = {A:1, J:1, S:1, B:2, K:2, T:2...};
var n = "lighthouse";
var nScore = 0;

for( var i = 0; i < n.length; i++ );
{
var curChar = n.charAt( i );
var curVal = dict[ curChar ];
nScore = nScore + curVal;
}

最佳答案

n[i]Character 类型,所以这应该是键类型字典而不是 String。值类型应为 Int:

let dict: [Character: Int] = ["a": 1, "j": 1, "s": 1, "b": 2, "k": 2, "r": 9 /* ... */]

您还必须定义一个用作分数的“默认值”对于字典中找不到的字符,可以这样做使用 nil-coalescing 运算符 ??:

let n = "lighthouse"
var nScore = 0

for i in n.indices[n.startIndex..<n.endIndex] {
let curChar = n[i]
let curVal = dict[curChar] ?? 0
nScore = nScore + curVal
}

或者更简单,直接枚举字符串的字符:

for c in n {
let curVal = dict[c] ?? 0
nScore = nScore + curVal
}

reduce() 更短:

let n = "lighthouse"
let nScore = n.reduce(0) { (score, c) in
score + (dict[c] ?? 0)
}

使用“速记参数”可以写得更紧凑:

let n = "lighthouse"
let nScore = n.reduce(0) { $0 + (dict[$1] ?? 0) }

如果它你可以完全控制可能的字符出现在输入字符串中,保证(!)字典为所有这些定义值然后你可以强制展开字典查找,例如

let n = "lighthouse"
let nScore = n.reduce(0) { $0 + dict[$1]! }

但是如果找不到字符,这将在运行时崩溃


如果你定义一个函数

func numericScore(_ str: String) -> Int {
return str.reduce(0) { $0 + (dict[$1] ?? 0) }
}

然后你可以轻松地将它应用到单个字符串

let nScore = numericScore("lighthouse")

或者将它映射到一个字符串数组上

let words = ["lighthouse", "motorcycle"]
let scores = words.map(numericScore)

或计算字符串数组的总分(再次使用 reduce):

let words = ["lighthouse", "motorcycle"]
let totalScore = words.reduce(0) { $0 + numericScore($1) }

// Alternatively in two steps:

let scores = words.map(numericScore)
let totalScores = scores.reduce(0, +)

关于javascript - 将字典值中的整数分配给字符串的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com