如何在python中使用字典将英语翻译成瑞典语

时间:2015-10-15 05:20:10

标签: python list dictionary

我正在使用以下代码,但显示一些错误 - 索引超出范围

english=["merry", "christmas", "and", "happy", "new", "year"]
swedish=["god","jul","och","gott","nytt","år"]
dict = {english[n]: swedish[n] for n in range(len(english))}#dictionary
trans_list=[]#list to save translated words

def trans(list):
    n=0
    for word1 in list:    
        for word2 in english: 
            if word1==word2:             
                       trans_list[n]=dict[word2]
                       n=n+1
                       print trans_list                 
list2=[]
list =["merry", "christmas", "and", "happy", "new", "year"]
trans(list)

2 个答案:

答案 0 :(得分:1)

以下是解决问题的另一种方法:

english = ["merry", "christmas", "and", "happy", "new", "year"]
swedish = ["god", "jul", "och", "gott", "nytt", "år"]

eng_swe_dict = {english: swedish for english, swedish in zip(english, swedish)}

def trans(word_list):
    return [eng_swe_dict[word] for word in word_list]

word_list = ["merry", "christmas", "and", "happy", "new", "year"]
print trans(word_list)

这将显示以下内容:

['god', 'jul', 'och', 'gott', 'nytt', 'år']

首先,您应该避免使用dictlist之类的变量名,因为它们是在Python命令中构建的。 Python不会抱怨,但你会重新分配意思。

您可以使用zip命令构建查找字典。在这种情况下,它会从您的两个列表中的每个列表中提取一个条目以提供给循环,然后将其用于构造字典。

Python list comprehension可用于创建翻译列表。对于每个单词,它会对其进行翻译并将其添加到新列表中。

答案 1 :(得分:0)

trans_list被定义为一个列表:

trans_list=[]

然而,这是一个空列表。因此,没有可用的索引,分配行失败:

trans_list[n]=dict[word2]

您可以做的只是将值附加到列表中:

trans_list.append(dict[word2])