Python小技巧 – True or False

  在昨天关于substring的blog中有如下一段代码:

image

也许你已经发现,在Python 3中其实有办法只用一行完成函数:

>>> def isSubstring2(s1,s2):
	return True if s2.find(s1)!=-1 else False

但是。。。还可以更简单吗?

如何更简单使用Python表达条件语句呢,just for fun :)

一种做法是使用列表索引:

>>> def isSubstring2(s1,s2):
	return [False,True][s2.find(s1)!=-1]
原理很简单,布尔值True被索引求值为1,而False就等于0. 还可以更简单么?留言给我吧 ;-)

posted on 2010-03-04 19:30 Freesc Huang 阅读(370) 评论(2) 编辑 收藏

评论

#1楼 2010-03-05 18:22 yanxy      

return s2.find(s1)+1
这个怎么样?因为0为false,非0为true。
另外,我觉你上篇文章《Python小技巧 - 子串查找》用in就很好,为什么这样做?我不太理解,是因为in的行为不确定吗?我初学Python
 回复 引用 查看   

#2楼[楼主] 2010-03-05 21:41 Freesc Huang      

@yanxy
hi,yanxy就本例来说,你的方法很好啊,之前那个用in也很好,我这里用的find不是最好的,这个例子只是用来说明单行条件语句的几种方法,不一定是find什么东西 ;-)
 回复 引用 查看   

<2012年2月>
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910

公告

These postings are provided "AS IS" with no warranties
and confer no rights.


Locations of visitors to this page

Blog Keywords
Embedded System,Visual Studio,.Net Framework,.Net Compact Framework,.Net Micro Framework,Windows Mobile,Windows Embedded CE,Emulator,WCF,CLR,Design & Pattern,C/C++,C#,Matlab,Algorithms
昵称:Freesc Huang
园龄:4年11个月
粉丝:32
关注:4

统计

  • 随笔 - 197
  • 文章 - 0
  • 评论 - 840

搜索

 

随笔分类(227)

随笔档案(197)

Blogs

Link

积分与排名

最新评论

阅读排行榜

评论排行榜

推荐排行榜