Shorten sequence of if statements
I have this code.
c = getch()
if c == "r": 开发者_如何学编程
return randrange(101, len(mylist) - 1)
if c == "u":
return 100
if c == "b":
return -2
if c == "w":
return -3
if c == "m":
return -4
if c == "d":
return -5
if c == "e":
return -6
if c == "k":
return -7
if c == "g":
return -8
if c == "p":
return -9
if c == "o":
right = center - 1
else:
left = center + 1
Can I make this code snippet more compact? How would you write it better?
thank you
You can use a dictionary:
# Special case.
if c == "r":
return randrange(101, len(list) - 1)
# This is constant. It could be generated once at program start.
d = { 'u' : 100, ...., 'p' : -9 }
# This covers the majority of the cases.
if c in d:
return d[c]
# Some more special cases.
if c == "o":
right = center - 1
else:
left = center + 1
I agree that a dictionary is the way to go. The problem with Mark's answer is that the dictionary gets rebuilt for every function call. The way around is to define the dict outside the function:
def foo():
c = getch()
if c in foo.mydict:
return foo.mydict[c]
else:
# TODO: special cases
foo.mydict = {'u':100, ... , 'p':-9}
# foo is now ready to use
You should strongly consider renaming your list
variable to something that isn't already used.
...
c=getch()
if c=="r":
return randrange(101, len(mylist) - 1)
return dict(u=100, b=-2, w=-3, m=-4, d=-5, e=-6, k=-7, g=-8, p=-9, o=center-1).get(c, center+1)
精彩评论