用于映射拼字游戏字母分布的字典理解

时间:2014-01-23 15:06:32

标签: python dictionary dictionary-comprehension

我有一个清单:

scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
               (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]

我必须写一个函数,它给出一个dict,其中包含一个得分映射的字母,只要上面的列表被传递。请帮助我编写函数... !!

5 个答案:

答案 0 :(得分:3)

用两个for循环来拯救Dict:...

letter_score = {letter: score for score, letters in scrabble_scores
                              for letter in letters.split()}

E.g。对于字符串中的每个字母(由空格分隔),在输出字典中生成一个键和值对;关键是字母,分数值。

演示:

>>> scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
...                (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
>>> letter_score = {letter: score for score, letters in scrabble_scores
...                               for letter in letters.split()}
>>> letter_score
{'A': 1, 'C': 3, 'B': 3, 'E': 1, 'D': 2, 'G': 2, 'F': 4, 'I': 1, 'H': 4, 'K': 5, 'J': 8, 'M': 3, 'L': 1, 'O': 1, 'N': 1, 'Q': 10, 'P': 3, 'S': 1, 'R': 1, 'U': 1, 'T': 1, 'W': 4, 'V': 4, 'Y': 4, 'X': 8, 'Z': 10}
>>> letter_score['Q']
10

奖金单词分数计算器:

>>> word = 'QUICK'
>>> sum(letter_score[c] for c in word)
20

其中word是一个仅包含(拼字)字母的大写字符串,忽略了双字母和三字母的评分。

答案 1 :(得分:1)

另一种更冗长的方式:

def makeScoreDict(scrabble_scores):
        score_dict = {}
        for row in scrabble_scores:
            for letter in row[1].split():
                score_dict[letter] = row[0]
        return score_dict

答案 2 :(得分:0)

在python中,你可以循环遍历这样的对:

for score, letters in scrabble_scores:
    print("{}: {}".format(letters, score))

这将给出结果:

"E A O I N R T L S U": 1
"D G": 2
...

在python中,您可以拆分包含空格的字符串:

>>> "E A O I N R T L S U".split()
['E', 'A', 'O', 'I', 'N', 'R', 'T', 'L', 'S', 'U']

现在只需将两者结合起来:

for score, letters in scrabble_scores:
    for letter in letters.split():
        # voila, you've got score and letter.

答案 3 :(得分:0)

这是你想要的吗?似乎是你所描述的。

scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
               (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
out_dict = {} 
for score in scrabble_scores:
    val = score[0]
    for letter in score[1].split():
        out_dict[letter] = val
print out_dict

答案 4 :(得分:0)

非字典理解答案。

scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
           (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]

d = dict()
for value,letters in scrabble_scores:
    d.update(dict(zip(letters.split(),[value]*len(letters.split())))

我肯定会把它作为一个dict comp,我确信这是OP的目的,但dict(zip(iter,iter))是值得一提的有用表达。