python的in,is和id函数

Posted 落日峡谷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的in,is和id函数相关的知识,希望对你有一定的参考价值。

1. in 和 not in —— 判断某个序列中是否存在某值

# in
aa = [1,2,3,Cathy,太平洋]
if 大西洋 in aa:
    print(yes)
else:
    print(no)  # no

# not in
if 大西洋 not in aa:
    print(yes)  # yes
else:
    print(no)
    
#-------------------------------------------------------
# 判断字符串是否存在某子串    
if 马来西亚 in 马来西亚是一个太平洋国家:   
    print(of course) # 输出 ‘of course‘

# ------------------------------------------------------
if 0 in (0,1,2,3):
    print(hhhh) #输出 ‘hhhh‘

if 0 in [0,1,2,3]:
    print(kkkk) #输出 ‘hhhh‘

2. is 和 is not —— 判断两个标识符是不是指向同一个地址(同一个对象),类似于判断 id(x) == id(y)

# 相同
bb = 234
cc = 234
if bb is cc:
    print(bb is cc)  #结果是 bb is cc 
else:
    print(bb is not cc)
print(id(bb))  # id()值一样
print(id(cc))

# 相同
bb = hhh
cc = hhh
if bb is cc:
    print(bb is cc)  #结果是 bb is cc 
else:
    print(bb is not cc)
    
# 相同
bb = hhh
cc = bb
if bb is cc:
    print(bb is cc)  #结果是 bb is cc 
else:
    print(bb is not cc)
print(id(bb))  # id()值一样
print(id(cc))

# 相同
bb = [1,2,3]
cc = bb
if bb is cc:
    print(bb is cc)  #结果是 bb is cc 
else:
    print(bb is not cc)

# 不相同
bb = [1,2,3]
cc = [1,2,3]
if bb is cc:
    print(bb is cc)   
else:
    print(bb is not cc) #结果是 bb is not cc
print(id(bb))  # id()值不一样
print(id(cc))

3. id() 函数,获取对象的内存地址(不同电脑不一样),例如:

bb = hhh
cc = bb
if bb is cc:
    print(bb is cc)  #结果是 bb is cc 
else:
    print(bb is not cc)
print(id(bb))  # id()值一样,均为 1680346901336
print(id(cc))

 

参考:

https://www.runoob.com/python/python-func-id.html

https://blog.csdn.net/zhangvalue/article/details/94598781

以上是关于python的in,is和id函数的主要内容,如果未能解决你的问题,请参考以下文章

python使用上下文对代码片段进行计时,非装饰器

Wordpress阻止访问wp admin€“wpsnipp.com网站你博客的Wordpress代码片段

Error: Python executable “H:devpython3.10python.EXE“ is v3.10.0, which is not supported by gyp.(代码片段

[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段

iOS一个'initWithRequest:delegate:' is deprecated: first deprecated in iOS 9.0 - Use NSURLSessi

pyhon学习第六天 代码块,小数据池(缓存机制,驻留机制),is == id =,字符编码