假设给出以下结构:
from django.utils.translation import ugettext_lazy as _
# Constants for all available difficulty types.
SIMPLE = 1
MEDIUM = 2
DIFFICULT = 3
# Names for all available difficulty types.
DIFFICULTIES = (
(SIMPLE, _("simple")),
(MEDIUM, _("medium")),
(DIFFICULT, _("difficult")),
)
如果给出常量,你如何获得字符串值?
一个循环很容易编程,但是有一个类似python的方式只有一个表达式吗?
表达式
难点[SIMPLE] [1]
返回字符串“medium”。显然是错的。
答案 0 :(得分:2)
当然你可以使用dict,但是给出了数组。
所以交换它。 (我假设你保留了收据..)
>>> dict(DIFFICULTIES)
{1: 'simple', 2: 'medium', 3: 'difficult'}
>>> d = dict(DIFFICULTIES)
>>> d[MEDIUM]
'medium'
通过一个未排序的元组搜索某些东西并不是解决问题的正确方法。我想你可以做到
>>> next(v for k,v in DIFFICULTIES if k == MEDIUM)
'medium'
如果你想避免带冒号的for循环,但这有点傻。
答案 1 :(得分:1)
它只是因为你指定了一个元组,一个从0开始的索引,你需要切换到字典或用正确的值修改你的常量:
DIFFICULTIES = {SIMPLE: "simple", MEDIUM: "medium", DIFFICULT: "difficult"}
OR:
SIMPLE, MEDIUM, DIFFICULT = range(3)
答案 2 :(得分:0)
使用字典:
SIMPLE, MEDIUM, DIFFICULT = range(3)
DIFFICULTIES = {
SIMPLE: _("simple"),
MEDIUM: _("medium"),
DIFFICULT: _("difficult")
}
DIFFICULTIES[SIMPLE] # will return "simple"