我正在尝试根据测试在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中三元运算符(单行条件语句)的工作方式。谢谢你!在
不,很遗憾,你不能使用三元运算符。顾名思义,它是一个运算符,因此左手边和右手边都必须是表达式。然而,与许多其他语言不同,Python assignments are statements,因此它们不能用来代替表达式。在
正如您正确指出的,解决方案是使用普通条件语句:
如果不坚持使用增广赋值,可以这样做:
感谢影游侠指出了我的错误(我错过了括号)。在
如果只需要增加两个变量-可以通过字典执行,代码如下:
或者相同,但更清楚:
^{pr2}$相关问题 更多 >
编程相关推荐