python - 有效地识别字符串的一部分是否在列表/字典键中?

标签 python string list match

<分区>

我在一个列表中有很多(>100,000)个小写字符串,其中一个子集可能如下所示:

str_list = ["hello i am from denmark", "that was in the united states", "nothing here"]

我还有一个这样的字典(实际上它的长度约为 ~1000):

dict_x = {"denmark" : "dk", "germany" : "ger", "norway" : "no", "united states" : "us"}

对于列表中包含任何字典键的所有字符串,我想用相应的字典值替换整个字符串。因此,预期结果应该是:

str_list = ["dk", "us", "nothing here"]

考虑到我拥有的字符串数量和字典的长度,最有效的方法是什么?

额外信息:一个字符串中的字典键永远不会超过一个。

最佳答案

这似乎是个好办法:

input_strings = ["hello i am from denmark",
                 "that was in the united states",
                 "nothing here"]
dict_x = {"denmark" : "dk", "germany" : "ger", "norway" : "no", "united states" : "us"}

output_strings = []

for string in input_strings:
    for key, value in dict_x.items():
        if key in string:
            output_strings.append(value)
            break
    else:
        output_strings.append(string)
print(output_strings)

关于python - 有效地识别字符串的一部分是否在列表/字典键中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49408938/

相关文章:

python - 如何从 Amazon S3 下载上个月创建的文件夹中的所有文件?

python - 将列表的元素作为 Python 中的单个项目返回

python - 使用 ChoiceField 时出现 Django Rest API TypeError

c# - 将双引号内联附加到字符串生成器时出现问题

C:使用列表的数组的最后一个元素

mysql - Wordpress:显示来自特定论坛的最新 3 个主题 bbpress、mysql 解决方案

python - 使用opencv python通过鼠标拖动来调整图像大小

php - 如何在 MySQL IN 语句中的内爆数组中的字符串周围添加撇号?

c++ - std::string s() 奇怪的行为

c# - 如何使用 C# 从 Windows 10 日历中检索 UWP 中的约会