規則:在字典中,每個鍵將是一個單詞 k,而值將是單詞 k 出現的輸入字串的索引串列。
單詞應僅被視為小寫。即 Hello 和 hello 應該被同等對待。
可以假設資料集將只包含字串串列。無需檢查資料集中元素的型別。
資料集中的字串資料將是干凈的。無需擔心清潔,即去除標點符號或數字。
在下面的示例中,該函式確定給定資料集中單詞的索引是什么。dataset 是包含字串的串列。
reverse_index 函式應該創建并回傳字典。
dataset = [
"Hello world",
"This is the WORLD",
"hello again"
]
res = reverse_index(dataset)
# This assertion checks if the result equals the expected dictinary
assert(res == {
'hello': [0, 2],
'world': [0, 1],
'this': [1],
'is': [1],
'the': [1],
'again':[2]
})
我不確定接下來要做什么,但這就是我開始的方式
dataset = [
"Hello world",
"This is the WORLD",
"hello again"
]
def reverse_index(dataset):
uj5u.com熱心網友回復:
您可以使用collections.defaultdict作為基礎和一個小回圈:
from collections import defaultdict
res = defaultdict(list)
for i,s in enumerate(dataset):
for w in set(map(str.lower, s.split())):
res[w].append(i)
dict(res)
輸出:
{'hello': [0, 2],
'world': [0, 1],
'is': [1],
'the': [1],
'this': [1],
'again': [2]}
uj5u.com熱心網友回復:
你可以試試這個方法
def reverse_index(data):
res = dict()
for i in range(len(data)):
for word in map(str.lower,data[i].split()):
if word not in res:
res[word] = [i,]
else:
res[word].append(i)
return res
輸出:
{
'hello': [0, 2],
'world': [0, 1],
'this': [1],
'is': [1],
'the': [1],
'again':[2]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342939.html
