python中=, ==, is, not, in的作用和区别

python中=, ==, is, not, in的作用和区别


=表示赋值的意思,这个比较简单

a = 3
a
3

==表示值判断

a == 3
True
# 同理 != 表示不等于
a != 3
False

is表示内存地址(引用)的一致性

a is 3
True

说明python会用一个pool的概念管理自己的变量,尤其在str这个类型的时候,我们再试试is

b = 3
a is b
True
id(a), id(b)
(1467921536, 1467921536)

好气, python内部优化没有创造多余的3例子都不好举了

b = 'str1'
b = 3
b is 3
True

哈,我们用复杂的数据类型试试

a = [1, [1, 4]]
b = [1, [1, 4]]
a is b
False

啦啦啦,复杂一些的数据结构python就有点顾不过来了

我们再这样:

a = [1, 4]
b = [23]
b.append(a)
b[-1] is a
True

现在可以初步窥探is用来判断内存地址(引用)的奥妙了吧, 而这样的引用(浅拷贝)又会带来很多的问题。以后在博客中再做默认浅拷贝的知识。

not

a = [1, 2]
b = [1, 2]
a is not b
True

单独使用not?

a = [1, 2, 4]
while True:
    if not a:
        break
    else:
        print(a.pop(0))
1
2
4

有点奇技淫巧了,一般我们这样写:

a = [1, 3, 4]
while a:
    print(a.pop(0))
1
3
4

这是因为[]在python中是等价None的,()也是


in

a = [1, 4]
b = [1, a]
b
[1, [1, 4]]
4 in b
False
[1, 4] in b
True
def in_func(idx, val):
    for item in iter(val):
        if item == idx:
            return True
    return False

print(in_func(4, b))
print(in_func([1, 4], b))
False
True
a = [1, 4]
b = [1, [1, 4]]
a in b, a is b[-1]
(True, False)

记住嵌套内容是无法in判断的,做一层迭代后的结果可以被识别出来,做的是值判断


你可能感兴趣的:(python中=, ==, is, not, in的作用和区别)