Python - 在三元运算符内循环

Python - loop inside 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

仍在接收指向 forSyntaxError。我也试过在不同的地方使用括号。

我环顾四周,还有其他相关话题,例如 this and this,这导致我尝试这样做:

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

我也通过搜索 Google 尝试了其他资源,但我不太明白。请教我。

谢谢

我认为这是最地道的代码编写方式:

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)

三元运算符的蓝图是:

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应该不需要评估

好的,所以使用您的示例有点棘手,因为三元运算符不能包含其特定蓝图之外的任何内容;那就是你要传递的 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))

希望对您有所帮助。