我的问题是:是否可以在回报中使用完整的条件语句(if,elif,else)?
我知道我可以这样做:
def foo():
return 10 if condition else 9
Run Code Online (Sandbox Code Playgroud)
我可以做这样的事情:
def foo():
return 10 if condition 8 elif condition else 9
Run Code Online (Sandbox Code Playgroud)
事后的想法:看一下这个表格看起来似乎不太可读,我的猜测是它可能没有任何有效的用例.无论如何,好奇心促使我问.提前感谢您的任何答案.
确实是!虽然应该谨慎使用,除非你是像Peter Norvig这样的专家(代码来自这里)!
def hand_rank(hand):
"Return a value indicating how high the hand ranks."
# counts is the count of each rank
# ranks lists corresponding ranks
# E.g. '7 T 7 9 7' => counts = (3, 1, 1); ranks = (7, 10, 9)
groups = group(['--23456789TJQKA'.index(r) for r, s in hand])
counts, ranks = unzip(groups)
if ranks == (14, 5, 4, 3, 2):
ranks = (5, 4, 3, 2, 1)
straight = len(ranks) == 5 and max(ranks)-min(ranks) == 4
flush = len(set([s for r, s in hand])) == 1
return (
9 if (5, ) == counts else
8 if straight and flush else
7 if (4, 1) == counts else
6 if (3, 2) == counts else
5 if flush else
4 if straight else
3 if (3, 1, 1) == counts else
2 if (2, 2, 1) == counts else
1 if (2, 1, 1, 1) == counts else
0), ranks
Run Code Online (Sandbox Code Playgroud)
为了澄清,您只需使用else if而不是elif在使用多个谓词编写Python"三元"语句时.