Returning conditional statements
本问题已经有最佳答案,请猛点这里访问。
我的问题是:是否可以在返回中使用完整的条件语句(if、elif或else)?
我知道我可以做到:
1 2 | def foo(): return 10 if condition else 9 |
我能这样做吗?
1 2 | def foo(): return 10 if condition 8 elif condition else 9 |
事后想:看看这个表单,它看起来不太可读,我猜它可能没有任何有效的用例。不管怎样,好奇促使我去问。提前感谢您的回答。
的确如此!尽管应该谨慎使用,除非你是像彼得·诺维格(这里的代码)这样的专家!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 |
为了澄清这一点,在用多个谓词组成python"ternary"语句时,只需使用
可以在外部三元的else子句中构造三元。
1 2 3 4 5 6 7 8 | a = 3 b = 2 def foo(): return 10 if a<b \ else 8 if a>b \ else 9 \ print(foo()) |