2016-10-03 95 views
-3

因此,我想添加另一個列表的相同索引的變量並將該變量添加到總數中。在這種情況下,我試圖讓這些分數等於拼字遊戲中的字母。添加相同索引的變量並添加到列表中

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]

所以我想a等於1並且c到等於3

說我有一個rack = ['c','a','t']
我怎麼可能讓'rack' == points = 5

這是我的預先存在的代碼:它給出了一個Out[1]: 87如果我說'c'和每個單個字母。

import random 

def load_words(): 
    """ 
    Returns a list of valid words. Words are strings of lowercase letters. 
    """ 
    # inFile: file 
    inFile = open('words.txt', 'r') 
    # line: string 
    line = inFile.readline() 
    # wordlist: list of strings 
    wordlist = line.split() 
    return wordlist 
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 
point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] 
bag_of_letters = [] 
for x in range(26): 
    for i in range(letter_count[x]): 
     bag_of_letters.append(letters[x]) 
rack = [] 
for i in range(7): 
    rack.append(bag_of_letters.pop(random.randint(0,len(bag_of_letters)-1))) 
print (rack) 
points = 0 
total_points = 0 
round_count = 10 
letterlst = [] 
while(round_count >= 0): 
    word = input("GIMME A LETTER TO COUNT THE SCORE OF: ") 
    for i in word: 
     letterlst += i 
    for let in word: 
     for letter in letters: 
      for word_rack in rack: 
       if let == word_rack: 
        points += point_values[letters.index(letter)] 
    total_points += points 
    if round_count == 0: 
     print("You have gotten",total_points,"points at the end of your round") 
    print(points,"points this round") 
    points = 0 
    round_count -= 1 
+3

我會建議你使用字典(字母值)而不是兩個列表。 – L3viathan

回答

3

下面是你的代碼的簡化版本:

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

>>> my_string = 'cat' 
>>> sum(point_values[letters.index(c)] for c in my_string) 
5 

說明:遍歷字符串中的每個字符。在letters列表中查找字符的索引。從point_values獲取該指數的值。總結所有的值。所有這些都是在最後一行代碼中完成的。 Python是MAGICAL。對? :)

0

這是你想要的嗎?

wordlist = ['why', 'are', 'you', 'doing', 'this'] 

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

score_list = [] 

for word in wordlist: 
    score = 0 
    for letter in word: 
     score += point_values[letters.index(letter)] 
    score_list.append(score) 

print score_list 

在你的代碼,我找不到letter_count定義,爲什麼你必須使用randint