簡體   English   中英

根據字典替換列表中值的Pythonic方法

[英]Pythonic way to replace values in a list according to a dictionary

我需要根據包含在 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]

對於有興趣在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會看到這個。

通過簡單的列表理解也很容易做到這一點。 無需使用 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)

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM