擅长:python、mysql、java
<p>对Daniel Roseman的<code>bisect</code>解决方案的一个小小改进是使用一个2元组列表:</p>
<pre><code>from bisect import bisect_right
RANKS = [
# max balance, rank
(500, 'Private'),
(1000, 'Private I'),
(1500, 'Private II'),
(2500, 'Private III'),
(3000, 'Corporal'),
# ...
(42000, 'Commander')
]
def get_rank(balance):
index = bisect_right(RANKS, (balance, ''))
try:
return RANKS[index][1]
except IndexError:
return RANKS[-1][1]
</code></pre>
<p>这里的优点是更容易一目了然,并且在编辑代码以引入新的列组、调整限制等时不容易出错</p>
<p>当提供的点数余额高于<code>RANKS</code>(在您的注释中指定)中的任何值时,它也返回最高等级,而不是引发异常。你知道吗</p>
<p>示例:</p>
<pre><code>>>> for n in range(0,42001,500):
... print("%5d %s" % (n, get_rank(n)))
... print("%5d %s" % (n + 1, get_rank(n + 1)))
...
0 Private
1 Private
500 Private
501 Private I
1000 Private I
1001 Private II
1500 Private II
1501 Private III
2000 Private III
2001 Private III
2500 Private III
2501 Corporal
3000 Corporal
# ...
42000 Commander
42001 Commander
</code></pre>