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

相关推荐