gpt4 book ai didi

Python 从项目列表中创建字典键

转载 作者:行者123 更新时间:2023-11-28 21:24:54 25 4
gpt4 key购买 nike

我希望使用 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

显然这是行不通的(列表是可变的,因此不能用作键(“不可散列类型:列表”))——那么生成来自几个已知属性的唯一键?

最佳答案

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

d[(attrib_a, attrib_b)] = t

括号可以省略:

d[attrib_a, attrib_b] = t

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

关于Python 从项目列表中创建字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com