在各种条件下在字典中搜索Swift

时间:2019-05-23 15:52:41

标签: swift dictionary search conditional-statements

我有简单的字典

var countOfR = ["R0": 0, "R1": 0, "R2": 0, "R3": 0, "R4": 0, "R5": 0, "R6": 0]

我需要通过多个条件检查此词典。例如,下一条语句可以完美运行:

for index in countOfR {
        if index == ("R0",2) || index == ("R1",2) || index == ("R2",2) || index == ("R3",2) || index == ("R4",2) || index == ("R5",2) || index == ("R6",2) {
            type = "P"

这将找到一个“对”。但是接下来,我需要检查“两对”-“ PP”。这样写是很糟糕的:

if index == ("R0",2) && index == ("R1",2) || index == ("R0",2) && index == ("R2",2) || index == ("R0",2) && index == ("R3",2) || index == ("R0",2) && index == ("R4",2) || index == ("R0",2) && index == ("R5",2) || index == ("R0",2) && index == ("R6",2) || ...

,依此类推...我还需要搜索“ pair and trine”,“ 3 Pairs”等。 为了更好地理解:

["R0": 1, "R1": 2, "R2": 1, "R3": 1, "R4": 0, "R5": 1, "R6": 0]是“ P”,

["R0": 1, "R1": 0, "R2": 0, "R3": 1, "R4": 0, "R5": 2, "R6": 0]也是“ P”,

["R0": 1, "R1": 0, "R2": 2, "R3": 1, "R4": 0, "R5": 2, "R6": 0]是“ PP”

如何解决此任务?请给我一些建议!

2 个答案:

答案 0 :(得分:0)

根据条件创建字典,然后通过比较条件字典来过滤主字典。将根据过滤的结果计数创建类型。

var condition = ["R0":2,"R1":2,"R2":2,"R3":2,"R4":2,"R5":2,"R6":2]

let test1 = ["R0": 1, "R1": 2, "R2": 1, "R3": 1, "R4": 0, "R5": 1, "R6": 0]// is "P",
let count1 = test1.filter { index in condition.contains(where: { $0 == index }) }.count
let type1 = String(repeating: "P", count: count1)
print(type1)//P

let test2 = ["R0": 1, "R1": 0, "R2": 0, "R3": 1, "R4": 0, "R5": 2, "R6": 0]// is "P" too,
let count2 = test2.filter { index in condition.contains(where: { $0 == index }) }.count
let type2 = String(repeating: "P", count: count2)
print(type2)//P

let test3 = ["R0": 1, "R1": 0, "R2": 2, "R3": 1, "R4": 0, "R5": 2, "R6": 0]// is "PP"
let count3 = test3.filter { index in condition.contains(where: { $0 == index }) }.count
let type3 = String(repeating: "P", count: count3)
print(type3)//PP

答案 1 :(得分:0)

您的这样的毫无意义,因为它永远不会true。您的index(或可能的名字)不能同时等于两个不同的事物。

我想您只需要计算值为2的条目数即可。

您可以这样写:

func getType(_ countOfR: [String: Int]) -> String {
    let pairs = countOfR.filter{$0.value == 2}.count
    let trines = countOfR.filter{$0.value == 3}.count
    let type = String(repeating: "P", count: pairs) + String(repeating: "T", count: trines)
    return type
}
print(getType(["R0": 1, "R1": 2, "R2": 1, "R3": 1, "R4": 0, "R5": 1, "R6": 0]))
//->P
print(getType(["R0": 1, "R1": 0, "R2": 0, "R3": 1, "R4": 0, "R5": 2, "R6": 0]))
//->P
print(getType(["R0": 1, "R1": 0, "R2": 2, "R3": 1, "R4": 0, "R5": 2, "R6": 0]))
//->PP