Python - 三元运算符

时间:2016-07-15 01:08:09

标签: python ternary-operator

我正在学习python,并尝试使用一些三元运算符。

我正在尝试使用三元组来创建下面的函数:

def array_count9(nums):
    count = 0
    for i in nums:
        if i == 9:
            count += 1
    return count

我试过了:

def array_count9(nums):
    count = 0
    count += 1 if i == 9 for i in nums else pass
    return count

扔了一个SyntaxError,然后环顾四周后发现this并更改了我认为更好的代码:

def array_count9(nums):
    count = 0
    count += 1 if i == 9 else pass for i in nums
    return count

仍在接收指向SyntaxError的{​​{1}}。我也试过在不同的地方使用括号。

我环顾四周,还有其他相关的帖子,例如thisthis,这导致我尝试了这个:

for

我也通过搜索Google尝试了其他资源,但我无法解决这个问题。请教我。

由于

3 个答案:

答案 0 :(得分:1)

我认为这是编写代码的最惯用的方式:

def array_count9(nums):
    return sum(num == 9 for num in nums)

但如果你想使用if / else结构,你也可以这样做:

def array_count9(nums):
    return sum(1 if num == 9 else 0 for num in nums)

答案 1 :(得分:1)

三元运营商的蓝图是:

condition_is_true if condition else condition_is_false

发生语法错误的语句位于

count += 1 if i == 9 else pass for i in nums

count += 1不符合蓝图规范,因为condition_is_true不需要进行评估。

答案 2 :(得分:0)

好的,所以使用你的例子有点棘手,因为三元运算符不能包含任何超出它的特定蓝图;作为for循环,你试图传递它。

count += 1 if i == 9 for i in nums else pass

所以在摆弄代码之后:

def array_count9(nums):
count = 0
count += 1 if i == 9 for i in nums else pass
return count

我确信你正在寻找涉及三元运算符和for循环的东西。所以记住你的目标,这就是我想出来的。

numss = [3,6,9,10,35]

def count9(nums):
    count = 0
    a = count + 1
    for i in nums:
        count = (a if i == 9 else count) #This being the ternary operator
    return count

print (count9(numss))

希望这有帮助。