tags:

views:

60

answers:

2

I had this:

    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)

Then I did this:

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

Is it possible to further simplify this and make it into a one-liner?

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

If you don't need to check for the setting being one of an acceptable number of values, it becomes:

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

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

or you could do it with a dictionary:

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

if Setting["Language"] in Linguas:
    f.m_radioBox3.SetSelection(Linguas[Setting["Language"]])
Noah
I didn't know about the .index, thanks. It works and keeps my list the same.
relima
+1 index is the best solution here. Using a dictionary would be overkill.
RevolXadda
I would create the dictionary like this: `Linguas = dict([(lang, i) for i, lang in enumerate(["en", "pt", "fr", "es"]))`
hughdbrown
@RevolXadda - I agree that in this trivial case a list is fine, but I believe understanding the concept of mapping values with a dictionary is important. Also, .index is an O(n) operation whereas dictionary lookup is O(1), so .index is much slower.
nearlymonolith