【问题标题】:Pythonic way to replace values in a list according to a dictionary根据字典替换列表中值的Pythonic方法
【发布时间】:2020-10-05 21:41:20
【问题描述】:

我需要根据 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,因此我需要一种有效的方法来执行此操作。

【问题讨论】:

  • 使用 pandas 可以吗?
  • 不,它不在 Pandas 中,如果可能,我不想将列表加载到 Pandas 中
  • 知道了!特别是对于大型列表,使用 pandas 可能会快得多。因此,如果您愿意,我可以将 pandas 解决方案作为一个小额外内容发布。 :)
  • 是的,绝对!我不喜欢使用 pandas,因为我正在从事一个目前尚未在 Pandas 中开发的大型项目。无论如何,如果可以节省很多时间,我可以考虑切换到 Pandas :)

标签: python python-3.x list dictionary replace


【解决方案1】:
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]

【讨论】:

  • 我接受这个答案,因为它明白了。只是为了分享,我添加了一个if 条件以检查令牌a 是否在inverse_dict 中:[inverse_dict[a] if a in inverse_dict.keys() else np.nan for a in lst]
  • @AndreaM 您可以使用 .get 来避免 if 条件。查看我的编辑。
【解决方案2】:

对于任何有兴趣在pandas这样做的人:

my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}
# revert the dict
my_dict_rev = {k2: k for k, v in my_dict.items() for k2 in v}
# convert the list to a pandas Series
ser = pd.Series(["hello", "word", "bye", "my", "friend", "hello"])
# replace the values
rev_ser = ser.replace(my_dict_rev)

我知道答案不是要求pandas 解决方案,但特别是对于大型 列表,pandas 可能会快得多。也可能其他已经在使用pandas 的人会看到这个。

【讨论】:

    【解决方案3】:

    通过简单的列表理解也很容易做到这一点。无需使用 Pandas 。

    lst = ["hello", "word", "bye", "my", "friend", "hello"]
    my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}
    
    result = []
    [result.append(k) for word in lst for k,v in my_dict.items() if word in v]
    
    print(result)
    

    输出:

    [0, 0, 2, 1, 1, 0]
    

    【讨论】:

    • 这不是正确的列表理解。查看@warped 的答案以了解正确列表理解的实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2015-10-30
    • 2018-01-10
    • 2021-07-13
    • 2015-03-20
    • 2019-07-21
    • 2019-11-19
    相关资源
    最近更新 更多