在for循环中通过三元运算符递增不同的变量

2024-09-28 22:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试根据测试在for循环中添加另一个变量:

for i in range(alist.__len__()):
        if alist[i] is not blist[i]:
            ascore +=1 if alist[i] > blist[i] else bscore+=1
    print(ascore,bscore)

此代码不起作用。我所理解的是if条件不适用于整个赋值(我们递增ascore if condition),而是应用于我的值1(我们将ascore增加1 if条件)。我更喜欢类似于第一个功能。我能在这里做点什么吗?我理解将其分解为elsif是否可以轻松地解决这个特定的问题,但我更感兴趣的是python中三元运算符(单行条件语句)的工作方式。谢谢你!在


Tags: 代码inforlenifisnotrange
3条回答

不,很遗憾,你不能使用三元运算符。顾名思义,它是一个运算符,因此左手边和右手边都必须是表达式。然而,与许多其他语言不同,Python assignments are statements,因此它们不能用来代替表达式。在

正如您正确指出的,解决方案是使用普通条件语句:

for i in range(len(list)):
        if alist[i] is not blist[i]:
            if alist[i] > blist[i]:
                ascore +=1 
            else:
                bscore +=1
    print(ascore, bscore)

如果不坚持使用增广赋值,可以这样做:

ascore, bscore = (ascore + 1, bscore) if alist[i] > blist[i] else (ascore, bscore + 1)

感谢影游侠指出了我的错误(我错过了括号)。在

如果只需要增加两个变量-可以通过字典执行,代码如下:

scores = {
    True: 0,   # ascore
    False: 0   # bscore
}

for i in range(len(alist)):
    if alist[i] is not blist[i]:
        scores[alist[i] > blist[i]] += 1

print(scores)

或者相同,但更清楚:

^{pr2}$

相关问题 更多 >