I have a list of strings paired with a number. I want to find the average value for each word that matches to a list of words. How can I do this?
Question: Below is an example of what I am referring to. 'injury' is located both in the
second and third string with a value of 100,000 and 50,000 respectively. So
the average value for injury would be 75,000. But 'slip' is only located in
the first string, so it would have an average value of 150,000. I would like
to apply this logic to analyze a database. Are there any suggestions on how to
approach this using 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)]
    


Answer: After stripping the syntax errors from your example, here's one solution using
loops. I don't think there's any neat comprehension you can pull off here, but
I'm eager to be proven wrong. I used floats for accuracy, convert to int as
needed. I also assumed the order of your `Output` does not matter, since I
cannot make out any intrinsic order that would make sense. That being said,
this should get you started:

    
    
    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])
    

Output:

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

