Andy
Andy

Reputation: 27

Letter scores in python

Here's the given scrabble score list:

 scrabbleScores = [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ] 

And I want to use the function " def letterScore(letter, scoreless): " that get the score of the letter. It looks like:

letterScore("c", scrabbleScores)
3

Please help, thanks.

Upvotes: 0

Views: 1603

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174796

You may use list_comprehension or dictionary method.

>>> scrabbleScores = [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ]
>>> def letterSCore(letter, lis):
    for i in lis:
        if i[0] == letter:
            return i[1]


>>> print(letterSCore("c", scrabbleScores))
3
>>> 

or

>>> def letterSCore(letter, lis):
    return next(i[1] for i in lis if i[0] == letter)

>>> print(letterSCore("c", scrabbleScores))
3

This would iterate over every item in the list and return item[1], ie item of index 1 only if the item of index 0 is equal to the letter you gave.

or

>>> dic = {i[0]:i[1] for i in scrabbleScores}
>>> dic["c"]
3

Upvotes: 0

Jose Haro Peralta
Jose Haro Peralta

Reputation: 999

As Paul Rooney has suggested, the easiest (and most efficient!) way is to use a dictionary instead of a list. However, if for whatever reason you still want or need to store the data in the form of a list, you can use the following function:

def letterScore(letter, scoreless):
    scoreless = dict(scoreless)
    print(scoreless[letter])

The function converts the list into a dictionary, in which you can then very easily and efficiently obtain the value through they key (which is the parameter that you request in the function).

Upvotes: 2

Related Questions