gpt4 book ai didi

根据字典替换列表中值的 Pythonic 方法

转载 作者:行者123 更新时间:2023-12-04 00:18:27 25 4
gpt4 key购买 nike

我需要根据 Python 字典中包含的值转换列表值。

我有一个如下列表:

lst = ["hello", "word", "bye", "my", "friend", "hello"]

还有一个使用集群过程获得的字典,所以键是标签,值是类别:

my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}

我需要更快地将原始列表转换为:

new_lst = [0, 0, 2, 1, 1, 0]

考虑在实际情况下,列表长度接近 60k,因此我需要一种有效的方法来执行此操作。

最佳答案

lst = ["hello", "word", "bye", "my", "friend", "hello"]
my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}

inverse_dict = {b:a for a,c in my_dict.items() for b in c}

new_lst = [inverse_dict.get(a) for a in lst]

关于根据字典替换列表中值的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62405818/

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