Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 在字典中查找部分值_Arrays_Swift_Dictionary_Search - Fatal编程技术网

Arrays 在字典中查找部分值

Arrays 在字典中查找部分值,arrays,swift,dictionary,search,Arrays,Swift,Dictionary,Search,我有以下字典: ["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"] 我需要对每个包含特定字符的键执行一次检查。例如,如果我查找'no',由于uno值,我只会得到key uno。如果我找“瓦尔”,我会得到三把钥匙 对于第二种情况,我需要获取数组中的所有键,例如[uno]和[uno,dos,tres] 我是swift的新手,但我正在为搜索构建一个虚拟应用程序,我不知道如何做到这一点。如果您对搜索功能有任何其他想法,我也会非常

我有以下字典:

["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]
我需要对每个包含特定字符的键执行一次检查。例如,如果我查找'no',由于uno值,我只会得到key uno。如果我找“瓦尔”,我会得到三把钥匙

对于第二种情况,我需要获取数组中的所有键,例如[uno]和[uno,dos,tres]

我是swift的新手,但我正在为搜索构建一个虚拟应用程序,我不知道如何做到这一点。如果您对搜索功能有任何其他想法,我也会非常感激地接受。

试试这个:

let dict = ["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]

let searchTerm = "val"
let keys = Array(
    dict.keys.filter { dict[$0]!.range(of: searchTerm, options: [.caseInsensitive]) != nil }
)

print(keys)
工作原理:

dict.keys.filter筛选字典中满足特定条件的所有键 dict[$0]!。rangeof:searchTerm,选项:[.不区分大小写]!=nil检查它包含搜索项的值 大堆将其转换为字符串数组,否则它是LazyFilterCollection 我的游乐场样本:

import Foundation

let dict = ["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]


let searchTerm = "val"

var result = dict.filter { 
    $0.value.range(of: searchTerm, options: [.caseInsensitive]) != nil
}.map{$0.key}


print(result) // ["tres", "uno", "dos"]

你的问题是关于Python还是Swift?如果只是其中一个标签,请删除另一个标签。如果两者都有关系,请把问题说清楚。所有键:dct.keys。密钥包含no:[x代表dct中的x.keys如果在x中为no]为什么要通过数组初始值设定项使用该表达式?@Alexander OP要求一个满足条件的密钥数组。如果没有这些,它仍然是一个懒散的过滤器集合。我认为值得一提的是,可能没有必要使用数组。例如,如果OP只想迭代这些键,那么它可以保持为LazyFilterCollectionBtw。您可以直接筛选字典,如下所示:dict.filter{},value.rangeof:searchTerm中的值,选项:[.casesensitive]!=nil}.map{$0.key}。它避免了对dict[$0]进行散列查找和展开的需要!原因。
import Foundation

let dict = ["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]


let searchTerm = "val"

var result = dict.filter { 
    $0.value.range(of: searchTerm, options: [.caseInsensitive]) != nil
}.map{$0.key}


print(result) // ["tres", "uno", "dos"]