3 回答

TA貢獻1860條經驗 獲得超8個贊
word 正在返回 a list。您需要循環/迭代該列表(單詞)。您可以通過以下方式完成它 -
data = ["Great price on the dewalt saw", "cool deal, love it", "nice find", "definitely going to buy"]
words = {'price': ['price', 'compare', '$', 'percent', 'money']}
for d in data:
for word in words.values():
for s in word :
if s in d:
print('Results:')
print(d)
words.values()上面的代碼將查找字典單詞中的值數組(即 - 中的任何列表)中的任何字符串是否是任何字符串的一部分data。
希望能幫助到你 !

TA貢獻1777條經驗 獲得超10個贊
您在這里遇到的問題是您有一個列表作為值,因此您的調用words.values()返回一個列表,該列表在內部包含另一個列表。您可以將其更改為for word in words['price']if you will only have a price key,或者您可以這樣更改它:
>>> words = {'price': ['price', 'compare', '$', 'percent', 'money']}
>>> [word for wordlist in words.values() for word in wordlist]
['price', 'compare', '$', 'percent', 'money']

TA貢獻1794條經驗 獲得超7個贊
可能是提高接受答案效率的好主意。
下面是一個提高時間復雜度的偽代碼(基于輸入)。
visited_dict = {}
results = {}
for d in data:
for k, word in words.items():
can_stop = False
res_val = []
for s in word:
# if same words from another key is searched
# Ex: words = {'price': ['price', 'compare', '$', 'percent', 'money'],
# 'price2':[ 'price', 'something', 'somethingelse']}
# In this case - get the result from visited dictionary to avoid
if s in visited_dict and s not in visited_dict[s]:
# save it to results
# skip further steps
continue
if s in d and s not in res_val:
# store it results
res_val.append(d)
# update visited dict
visited_dict[s] = d
# Save the result to final key to result map
results[k] = res_val # {'price': 'Great price on the dewalt saw'}
# To avoid duplicate
if res_val:
break
注意:它沒有經過測試或完全實現的代碼。是的,一旦正確實施,它可能會增加空間復雜性。
添加回答
舉報