座机 发表于 2017-4-23 10:46:52

python 三目运算(转)

Python代码  


[*]>>> a = 'abc'  
[*]>>> b = 'efg'  
[*]>>> 1==0 and a or b  
[*]'efg'  
[*]>>> 1>2 and a or b  
[*]'efg'  
[*]>>> 1<2 and a or b  
[*]'abc'  

  在如: a = '' 的话
Python代码  


[*]>>> a = ''  
[*]>>> 1<2 and a or b  
[*]'efg'  
[*]>>> 1>2 and a or b  
[*]'efg'  

  结果与我们要的不符.这个东西具体可以参考 dive into python  http://www.woodpecker.org.cn/diveintopython/
  因为,在 and or运算中 空字符串 ‘’,数字0,空列表[],空字典{},空(),None,在逻辑运算中都被当作假来处理
  解决办法:
Python代码  


[*]>>> (1<2 and  or )[0]  
[*]''  
[*]>>> (1>2 and  or )[0]  
[*]'efg'  

  这些基础还得多看看python语法
页: [1]
查看完整版本: python 三目运算(转)