问题描述
输入:word_types的列表,例如[“动词”,“形容词”,“名称”,“名词”
所需输出:一个字典,每个字典由word_type排列的每个字母-word_type组合三个单词。
即
{“动词”:[“ Averb1”,“ Averb2”,“ Averb3”],[Bverb1,...],...,“形容词”:[“ Aadjective1”,“ Aadjectives2”,“ Aadjectives3” ] ...等
这就是我用来生成数据的东西。
import string
A_to_Z = list(string.ascii_uppercase) # list of letters a-z
lettered_word_types = ["verb","adjective","name","noun"]
class Lexicon:
def __init__(self,testing = True):
if testing == True:
for TYPE in lettered_word_types:
setattr(self,TYPE + "s",[letter + TYPE for letter in A_to_Z])
self.__dict__ = {key: [[element + "1",element + "2",element + "3"] for element in value] for key,value in self.__dict__.items()}
data = Lexicon().__dict__
解决方法
该类没有用,只会混淆您在做什么。要音译代码以直接使用dict
,您只需要:
result = {}
for TYPE in lettered_word_types:
result[TYPE + 's'] = [letter + TYPE for letter in A_to_Z]
result = {key: [[element + "1",element + "2",element + "3"] for element in value] for key,value in result.items()}
所以,为了证明这确实是等效的:
In [1]: import string
...: A_to_Z = list(string.ascii_uppercase) # list of letters a-z
...: lettered_word_types = ["verb","adjective","name","noun"]
...:
...: class Lexicon:
...: def __init__(self,testing = True):
...: if testing == True:
...: for TYPE in lettered_word_types:
...: setattr(self,TYPE + "s",[letter + TYPE for letter in A_to_Z])
...: self.__dict__ = {key: [[element + "1",value in self.__dict__.items()}
...:
...:
...: data = Lexicon().__dict__
In [2]: result = {}
In [3]: for TYPE in lettered_word_types:
...: result[TYPE + 's'] = [letter + TYPE for letter in A_to_Z]
...:
In [4]: result = {key: [[element + "1",value in result.items()}
In [5]: result == data
Out[5]: True