有没有一种不太奇怪的方法来生成这个虚拟数据?

输入:word_types 列表,例如 ["verb", "adjective", "name", "noun]


期望的输出:按 word_type 排列的每个字母-word_type 组合的三个单词的字典。


IE


{“动词”:[“Averb1”,“Averb2”,“Averb3”],[Bverb1,...],...,“形容词”:[“Aadjective1”,“Aadjectives2”,“Aadjectives3”] .. 。 ETC


这是我用来生成数据的内容。


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__


30秒到达战场
浏览 85回答 1
1回答

冉冉说

该类没有任何作用,它只是混淆了你正在做的事情。要将代码音译为dict直接使用 a,您只需要: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", element + "2", element + "3"] for element in value] for key, 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", element + "2", element + "3"] for element in value] for key, value in result.items()}In [5]: result == dataOut[5]: True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python