返回条件语句

时间:2018-04-12 01:11:28

标签: python python-3.x

我的问题是 :是否可以在回复中使用完整的条件语句(if,elif,else)?

我知道我可以这样做:

def foo():
    return 10 if condition else 9

我可以做这样的事情:

def foo():
    return 10 if condition 8 elif condition else 9

事后补充 :看一下这个表单,它看起来似乎不太可读,我的猜测是它可能没有任何有效的用例。无论如何,好奇心促使我问。提前感谢您的任何答案。

2 个答案:

答案 0 :(得分:5)

肯定是!虽然应该谨慎使用,除非你是Peter Norvig的专家(code taken from here)

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“三元”语句时,只需使用else if而不是elif

答案 1 :(得分:3)

你可以在外三元的else子句中构造一个三元组。

a = 3
b = 2
def foo():
    return 10 if a<b     \
           else 8 if a>b \
           else 9        \

print(foo())