假设我有
class AType(models.IntegerChoices):
ZERO = 0, 'Zero'
ONE = 1, 'One'
TWO = 2, 'Two'
Django 3.2。
则AType.choices
可以用作dict,例如AType.choices[0]
或AType.choices[AType.ZERO]
是"零"。
从字符串映射到int(0,1,2(的最简单方法是什么,例如,将"Zero"映射到0?
我可以通过迭代每个键、值对来创建另一个dict,然后使用另一个。然而,我想知道是否有更方便的方法。
这在某种程度上与这个问题(另一种方式(、这个问题(没有答案(或这个问题(也没有答案(有关。
EDIT:这是我当前的解决方案,它只是手工编码的。
@classmethod
def string_to_int(cls, the_string):
"""Convert the string value to an int value, or return None."""
for num, string in cls.choices:
if string == the_string:
return num
return None
这是我当前的解决方案,它只是手工编码的。
@classmethod
def string_to_int(cls, the_string):
"""Convert the string value to an int value, or return None."""
for num, string in cls.choices:
if string == the_string:
return num
return None
您可以创建一个映射,然后通过密钥进行简单的dict访问:
label_mapping = {label: value for value, label in AType.choices}
# outputs: { 'Zero': 0, 'One': 1, 'Two': 2 }
@classmethod
def string_to_int(cls, the_string):
"""Convert the string value to an int value, or return None."""
return label_mapping.get(the_string)