codeforfun
codeforfun

Reputation: 187

Assign a score to a word in a list

I have a dictionary and a list with sublist with words:

d={"love":3, "good":2}
l=[["love", "apple", "same"],["good", "GOOD", "year"]]

If the word in the list is not in dictionary keys I need to assign a value of 3 to that word and sum the value of the sublist. In the example the outcome of the values would be:

[6, 3]

I have tried this code:

def scoring():
    score1=[]
    for sublst in l:
        for val in sublst:
            if val.lower() not in d.get(val.lower(), 0):
                score1=sum(3 for val in sublst)
        print(score1)

Upvotes: 1

Views: 239

Answers (1)

CDJB
CDJB

Reputation: 14536

The following list comprehension will provide the expected result:

>>> [sum(3 if w.lower() not in d else 0 for w in sl) for sl in l]
[6, 3]

To correct the function in your question:

def scoring():
    score1=[]
    for sublst in salida_tweets_separado:
        s = 0
        for val in sublst:
            if val.lower() not in valores:
                s += 3
        score1.append(s)
    print(score1)

Upvotes: 1

Related Questions