三元运算符语法错误

时间:2019-08-12 00:05:43

标签: python-3.x

我正在尝试使用三元运算符,但我想使用它们将值设置为False或True,但是出现错误。你们知道我在做什么错吗?

List<BarItem> barItems = [ BarItem( text: "Messages", iconData: Icons.message, color: Colors.pinkAccent, ),/* BarItem( text: "Friends", iconData: Icons.people, color: Colors.teal, ),*/ BarItem( text: "Search", iconData: Icons.search, color: Colors.yellow.shade900, ),/* BarItem( text: "Profile", iconData: Icons.person_outline, color: Colors.lime.shade500, ),*/ BarItem( text: "Settings", iconData: Icons.settings, color: Colors.blue, ), ];

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式解决当前的问题:

play = False if ans.lower() is 'n' else True
else之后

没有额外分配。三元组的基本思想是:

finalValue = valueOne if someCondition else valueTwo

但是,(1)还有其他问题,所以我建议更简洁:

play = (ans.lower() != 'n')

(1)其中包括is检查身份相等,而不是 value 相等的事实。参见,例如:

>>> x = 9999
>>> y = 9999
>>> x == y
True
>>> x is y
False

您会注意到,即使两个对象具有相同的值,它们也是不同的。

其次,如果您要使用布尔值来输入值,那么实际上并不需要 三元,只需使用布尔值运算符就可以对其进行操作。

任何三元形式:

True if condition else False
False if condition else True

最好分别表达为:

condition
not condition

答案 1 :(得分:-1)

您的代码中存在一些常见的初学者错误。首先,play = True是Python语句,因此不能在三元运算符中使用(请参阅我对这个问题的评论)。

play = False if ans.lower() is 'n' else play = True

可以替换为

play = False if ans.lower() is 'n' else True

进一步简化为

play = not (ans.lower() is 'n')

令人沮丧的是,我们发现play始终是True。特别是,'N'.lower() is 'n'的值为False。这是因为is在我们处理同一字符串的两个不同副本时会检查两个对象是否相同。可以使用id函数直接检查:

In [234]: id('n'.lower())                                                
Out[234]: 4762431984

In [235]: id('n')                                                        
Out[235]: 4460608064

因此,not ('N'.lower() is 'n')not False的值为True。 因此,相反,我们应该使用play = not (ans.lower() == 'n'),或者更好的play = ans.lower() != 'n'

==is的上述区别在小型int上有明显的例外。例如,

In [236]: 1+1 is 2                                                       
Out[236]: True

对于大型int,这不再适用;例如

In [275]: 26 ** 26 is 26 ** 26                                           
Out[275]: False

(在我的情况下,对于OSX上的Python 3.7.1;此行为可能与早期版本的Python不同。)

出于完整性考虑,值得注意的是a is b并不总是暗示a == b。例如,

In [246]: x = np.nan                                                     

In [247]: x is x                                                         
Out[247]: True

In [248]: x == x                                                         
Out[248]: False