我想总结一个列表中的每个元素,哪些值可以通过匹配列表中的单词来实现。包含每个单词值的元组和包含短语的列表如下:
val_tuple = [('and',3),('cat',2),('dog',3),('only',5),('horse',3),('car',3),...]
word_list = ['cat and dog',
'only horse',
'dog and horse',
'only dog',...]
输出应该是这样的:
result = [('cat and dog', 8),
('only horse', 8),
('dog and horse', 9),
('only dog', 8),...]
我想不出办法,尝试了几次,只是为了总结列表中的值:
for w in word_list:
for val in val_tuple:
if val[0] in w:
sum = val[0]
sum += sum
最佳答案
首先你最好为你的单词值构造一个字典:
word_values = dict(val_tuple)
您可以简单地使用列表理解:
result = [(sentence,<b>sum(word_values.get(word,0) for word in sentence.split())</b>)
for sentence in word_list]
粗体部分总结了分数。所以我们对每个 sentence
做的是我们使用 .split()
来获取单词。现在,对于这些单词中的每一个,我们都获得了 word_values.get(word,0)
:这意味着我们执行查找,如果未找到该元素,我们假设单词值0. 我们对所有这些值进行sum(..)
,并为每个句子返回一个元组(sentence,sum(..))
。
根据提供的样本数据,我得到:
>>> result
[('cat and dog', 8), ('only horse', 8), ('dog and horse', 9), ('only dog', 8)]
关于python - 在与 Python 2.7 中的元组中的单词相匹配的列表中总结成员元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42511716/