又一个列表理解问题

时间:2010-10-20 00:19:56

标签: python list-comprehension

我有这个:

    if Setting["Language"] == "en":
        f.m_radioBox3.SetSelection(0)
    elif Setting["Language"] == "pt":
        f.m_radioBox3.SetSelection(1)
    elif Setting["Language"] == "fr":
        f.m_radioBox3.SetSelection(2)
    elif Setting["Language"] == "es":
        f.m_radioBox3.SetSelection(3)

然后我这样做了:

    Linguas = ["en","pt","fr","es"]
    a = 0
    for i in Linguas:
        if i == Setting["Language"]:
            f.m_radioBox3.SetSelection(a)
        a += 1

是否有可能进一步简化这一过程并使其成为单线?

2 个答案:

答案 0 :(得分:3)

mapping = {"en" : 0, "pt" : 1, "fr" : 2, "es" : 3}
if Setting["Language"] in mapping:
    f.m_radioBox3.SetSelection(mapping[Setting["Language"]])

如果您不需要检查设置是否为可接受数量的值之一,则变为:

mapping = {"en" : 0, "pt" : 1, "fr" : 2, "es" : 3}
f.m_radioBox3.SetSelection(mapping[Setting["Language"]])

答案 1 :(得分:3)

Linguas = ["en","pt","fr","es"]

if Setting["Language"] in Linguas:
    f.m_radioBox3.SetSelection(Linguas.index(Setting["Language"]))

或者你可以用字典做到这一点:

Linguas = {"en":0,"pt":1,"fr":2,"es":3}

if Setting["Language"] in Linguas:
    f.m_radioBox3.SetSelection(Linguas[Setting["Language"]])