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
注意:它没有经过测试或完全实现的代码。是的,一旦正确实施,它可能会增加空间复杂性。
添加回答
举报