为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

30秒到达战场 2023-10-18 16:07:49
输入:word_types 列表,例如 ["verb", "adjective", "name", "noun]期望的输出:按 word_type 排列的每个字母-word_type 组合的三个单词的字典。IE{“动词”:[“Averb1”,“Averb2”,“Averb3”],[Bverb1,...],...,“形容词”:[“Aadjective1”,“Aadjectives2”,“Aadjectives3”] .. 。 ETC这是我用来生成数据的内容。import stringA_to_Z = list(string.ascii_uppercase)  #  list of letters a-zlettered_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__
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超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 == data

Out[5]: True


查看完整回答
反对 回复 2023-10-18
  • 1 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信