【问题标题】:Python creating dictionary key from a list of itemsPython从项目列表中创建字典键
【发布时间】:2015-06-09 14:21:44
【问题描述】:

我希望使用 Python 字典来跟踪一些正在运行的任务。这些任务中的每一个都有许多使其独一无二的属性,所以我想使用这些属性的函数来生成字典键,这样我就可以使用相同的属性再次在字典中找到它们;类似于以下内容:

class Task(object):
    def __init__(self, a, b):
        pass

#Init task dictionary
d = {}

#Define some attributes
attrib_a = 1
attrib_b = 10

#Create a task with these attributes
t = Task(attrib_a, attrib_b)

#Store the task in the dictionary, using a function of the attributes as a key
d[[attrib_a, attrib_b]] = t

显然这不起作用(列表是可变的,因此不能用作键(“unhashable type: list”)) - 那么生成来自多个已知属性的唯一键?

【问题讨论】:

    标签: python hash dictionary


    【解决方案1】:

    使用元组代替列表。元组是不可变的,可以用作字典键:

    d[(attrib_a, attrib_b)] = t
    

    括号可以省略:

    d[attrib_a, attrib_b] = t
    

    但是,有些人似乎不喜欢这种语法。

    【讨论】:

      【解决方案2】:

      使用元组

      d[(attrib_a, attrib_b)] = t
      

      应该没问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-09
        • 1970-01-01
        • 1970-01-01
        • 2019-05-25
        • 1970-01-01
        • 2013-10-26
        • 2017-05-05
        • 2020-11-17
        相关资源
        最近更新 更多