【发布时间】: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