Home  >  Article  >  Backend Development  >  python使用in操作符时元组和数组的区别分析

python使用in操作符时元组和数组的区别分析

WBOY
WBOYOriginal
2016-06-06 11:16:511221browse

在python中可以使用in符号判断指定的元素是否存在于列表中,但我发现元组和数组存在区别,下面是详细实验结果。

>>> 'bitsCN.com' in ['haotu.net','bitsCN.com']
True
>>> 'bitsCN.com' in ('haotu.net','bitsCN.com')
True
 
>>> 'bitsCN.com' in ['bitsCN.com/codes','haotu.net']
False
>>> 'bitsCN.com' in ('bitsCN.com/codes','haotu.net')
False
 
>>> 'bitsCN.com' in ['bitsCN.com/codes']
False
>>> 'bitsCN.com' in ('bitsCN.com/codes')
True

前面5条测试都符合我们的预期,只有最后一条,将数组换成元组后,在元组中只有一个元素的时候,python居然是把元组当成了字符串处理,不知道为什么会有这样的处理方式,但开发的时候却要注意,只用in语句判断数组中是否存在制定元素时,最好用[]的数组,而非元组

以上所述就是本文的全部内容了,希望大家能够喜欢。

Statement:
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