Python返回真假值(True or False)小技巧

WBOY
Release: 2016-06-10 15:15:34
Original
1653 people have browsed it

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

也许你已经发现,在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. 还可以更简单么?留言给我吧 ;-)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!