xra*_*alf 1 python if-statement coding-style
我有这个代码.
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
Run Code Online (Sandbox Code Playgroud)
我可以使这段代码更紧凑吗?你会怎么写得更好?
谢谢
你可以使用字典:
# 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
Run Code Online (Sandbox Code Playgroud)