Python 我有一个字符串列表和一个数字。我想找到与单词列表匹配的每个单词的平均值。我该怎么做?

Python 我有一个字符串列表和一个数字。我想找到与单词列表匹配的每个单词的平均值。我该怎么做?,python,Python,下面是我指的一个例子“伤害”位于第二个和第三个字符串中,值分别为100000和50000。所以受伤的平均值是75000。但“滑移”仅位于第一个管柱中,因此其平均值为150000。我想将此逻辑应用于分析数据库。对于如何使用python实现这一点,有什么建议吗 word_list = ['loss', 'fault', 'slip', 'fall', 'injury'] data_list = [('there was a slip and fall', 150000), ('injury and

下面是我指的一个例子“伤害”位于第二个和第三个字符串中,值分别为100000和50000。所以受伤的平均值是75000。但“滑移”仅位于第一个管柱中,因此其平均值为150000。我想将此逻辑应用于分析数据库。对于如何使用python实现这一点,有什么建议吗

word_list = ['loss', 'fault', 'slip', 'fall', 'injury']

data_list = [('there was a slip and fall', 150000), ('injury and loss', 100000), ('injury at fault', 50000)]

Output = [('injury', 75000), ('loss', 100000), ('slip', 150000), ('fall', 150000), ('fault', 50000)]

从示例中去除语法错误后,下面是一个使用循环的解决方案。我不认为你能在这里做出任何清晰的理解,但我渴望被证明是错的。我使用浮点数来提高精度,根据需要转换为int。我还假设
输出的顺序无关紧要,因为我无法理解任何有意义的内在顺序。也就是说,这应该让你开始:

from collections import defaultdict
d = defaultdict(dict)
word_list = ['loss', 'fault', 'slip', 'fall', 'injury']
data_list = [('there was a slip and fall', 150000), ('injury and loss', 100000), ('injury at fault', 50000)] 
split_list = [(set(x.split()), y) for x,y in data_list]

for word in word_list:
    for stringset, count in split_list:
        if word in stringset:
            d[word]['seen'] = d[word].get('seen', 0) + 1
            d[word]['count'] = d[word].get('count', 0) + count

print([(word, float(d[word]['count'])/d[word]['seen']) for word in d])
输出:

[('loss', 100000.0), ('injury', 75000.0), ('fall', 150000.0), ('slip', 150000.0), ('fault', 50000.0)]

虽然我希望有,但没有专门用于编写代码的stackexchange站点。如果您的代码有问题,我们会尽力帮助您,但我们不会为您编写。@Cole您让它工作了吗?