我有这样一个函数:
def GetMapping(mappings, key):
mapping = mappings.get(key)
if mapping is None:
currentMax = mappings.get("max", 0)
mapping = currentMax + 1
mappings["max"] = mapping
mappings[key] = mapping
return mapping, mappings
基本上,给定一个字典mappings
和一个键key
,函数返回与键相关的值(如果存在)。你知道吗
如果没有,它将在字典中查找存储在键“max”下的当前最大id,将其分配给该键,并更新max的值
我想知道是否有一个内置的/不那么冗长的方式来实现这一点?你知道吗
您可以将} 方法。你知道吗
dict
子类化并重写^{正如@Code学徒指出的,最好在
__init__
方法中设置一个max
属性。这避免了潜在的密钥冲突(即,恰好命名为"max"
的密钥)。你知道吗假设您实际上不需要/想要一个可以从外部控制的
'max'
项,而只需要自动递增的id:演示:
相关问题 更多 >
编程相关推荐