python if statement too long and ugly, is there a way to shorten it
This question already has an answer here:
有一个包含给定p的y值的字典
p={"A":10,.....}
y=dict[p]
There is no possibility to shorten this piece of code. As you may have noticed, python does not provide any switch-case statement.
Depending on your usage, you could change it to a dictionary or recalculate it by value:
values = { "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15 }
y = values[p]
or
y = ord(p) - ord("A") + 10
Use a dict:
choice = {
"A": 10,
"B": 11,
"C": 12,
"D": 13,
"E": 14,
"F": 15
}[selected]
ie.
selected = "A"
choice = {
"A": 10,
"B": 11,
"C": 12,
"D": 13,
"E": 14,
"F": 15
}[selected]
print choice
>>> 10
By immediately adding the [selected]
at the end of the dict can easily get a dictionary to behave like a control flow statement. Using this pattern it will always evaluate to the case.