【问题标题】:How to make a category inside a category with python?如何用python在一个类别中创建一个类别?
【发布时间】:2021-07-26 16:25:49
【问题描述】:

我想构建一个应用程序,将您的照片分类管理,您只需首先放置它们的路径,然后使用关键字访问这些照片。当我必须创建一个子类别时,我被卡住了。我试过了

path_and_image = {user_answer : new_list, new_list : path_LiL}

其中 user_answer 是主要类别,new_list 是子类别/类别,path_LiL 是它们的路径。它给了我回溯 TypeError: unhashable type: 'list'。我不知道如何解决这个问题,希望有人能解决我的问题。

我也尝试了其他东西,比如 stackoverflow 中的一个函数:

                                        [lista_noua],
                                    [lista_noua] ,
                                        [path_LiL]]

                    def make_trie(path_and_image):
                        root = dict()
                        for i in path_and_image:
                            current_dict = root
                            for letter in i:
                                current_dict = current_dict.setdefault(letter, {})

                        return root
                    trie = make_trie(path_and_image)
                    print(trie)

它仍然给出同样的错误。

【问题讨论】:

  • 您的所有类别都有子类别?多少级?嵌套字典会帮助你,但你做错了。
  • 修复缩进

标签: python python-3.x dictionary nested categories


【解决方案1】:

您尝试将列表作为字典中的键。特别是字典的第二个元素中的new_list。那是你的错误。

一个很好的解决方案:

path_and_image = {user_answer : new_list, 'paths': path_LiL}

您注意到'paths' 是一个字符串。

【讨论】:

  • 那么你确实需要一个嵌套字典。
  • 我希望 new_list 中的每个字符串都将其路径作为图像,因为我不知道用户会将其中的字符串替换为关键字,我的意思是如果我那里有一个名为“课程”的类别我想要数学和英语,从那里我想为每个类别放置一些照片路径,然后当用户说课程然后在另一个输入数学时,程序应该向他打开一个或多个图像取决于他放了多少,但我不知道他们的关键词把它放在我的字典里。不过我会试试的,谢谢。
【解决方案2】:

为什么不使用嵌套字典? (列表不能作为键,因为它不是可散列的,即它的值可以随时间变化,只有字符串、元组等不可变对象可以用作键)


继续回答:

考虑一下-

Category Colors
  | Red
  | Pink
  | Blue
Category Material
  | Matte
  | Polish
  | Plain
Category Other
  | ...

代码

colors = ['Red', 'Pink', 'Blue']
material = ['Matte', 'Polish', 'Plain']

categories = {'colors': colors, 'material': material}

即使你有更多的关卡——你也应该去......

Category Colors
  | Red
     | Dark Red
     | Light Red
  | Pink
     | Dark Pink
     | Light and Dark Pink
  | Blue
Category Material
  | Matte
  | Polish
  | Plain
Category Other
  | ...

这里,

colors = {'Red': ['Dark Red', 'Light Red'],
          'Pink': ['Dark Pink', 'Dark & Light Pink'],
          'Blue': ['Blue']}

material = {'Matte': ['Matte'],
            'Polish': ['Polish'],
            'Plain': ['Plain']}

categories = {'colors': colors, 'material': material}

当然,它值得更好的答案 - 但现在你可以开始使用它了。

但是请记住,应该有一致性,如果您在一个类别中有多个级别,那么其他类别也应该具有相同的数据结构,否则在迭代它们时会遇到问题。

谢谢!

【讨论】:

  • 嗯,我不知道用户输入可以预先制作类别,这就是为什么我不放字符串因为我已经不知道了。无论如何,谢谢,我会试试的。
猜你喜欢
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 2011-12-19
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多