在 Python 中,集合是一种非常有用的数据结构,用于存储无序且唯一的元素。判断一个集合是否为空是很常见的操作,本文介绍了几种判断 Python 集合是否为空的方法。理解这些方法有助于我们更高效地操作和利用集合这个数据结构。

使用 len() 方法

使用 len() 方法返回集合的元素数量,如果为零,则表示该集合为空,否则不为空。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def is_empty(s):
return len(s) == 0

empty_set = set()
not_empty_set = set([1, 2, 3])

print("`empty_set` is empty?", is_empty(empty_set))
print("`not_empty_set` is empty?", is_empty(not_empty_set))

"""
Output:
`empty_set` is empty? True
`not_empty_set` is empty? False
"""

使用 not 关键字

Python 的 not 关键字是一个逻辑运算符,用于计算出操作数的否定或相反的布尔值:not TrueFalsenot FalseTrue

若集合 S 为空,则 not STrue,若不为空,则 not SFlase

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def is_empty(s):
return not s

empty_set = set()
not_empty_set = set([1, 2, 3])

print("`empty_set` is empty?", is_empty(empty_set))
print("`not_empty_set` is empty?", is_empty(not_empty_set))

"""
Output:
`empty_set` is empty? True
`not_empty_set` is empty? False
"""

使用 bool() 方法

Python 的 bool() 方法可以将任意类型转换为布尔值。

转换规则如下:

  • 以下值转换为 False:
    • False
    • None
    • 0
    • 空字符串 ‘’
    • 空列表 []
    • 空元组 ()
    • 空字典 {}
  • 其他值转换为 True

我们可以借助 bool() 方法来判断一个集合是否为空,示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def is_empty(s):
return bool(s) == False

empty_set = set()
not_empty_set = set([1, 2, 3])

print("`empty_set` is empty?", is_empty(empty_set))
print("`not_empty_set` is empty?", is_empty(not_empty_set))

"""
Output:
`empty_set` is empty? True
`not_empty_set` is empty? False
"""

NOTE:这里的 bool(s) == False 可以写成 not bool(s),最终可简写为 not s

与空集合比较

如果一个集合 S 与空集合相等,则说明该集合也是一个空集合。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def is_empty(s):
return s == set()

empty_set = set()
not_empty_set = set([1, 2, 3])

print("`empty_set` is empty?", is_empty(empty_set))
print("`not_empty_set` is empty?", is_empty(not_empty_set))

"""
Output:
`empty_set` is empty? True
`not_empty_set` is empty? False
"""

小结

判断 Python 集合是否为空有以下四种方法:

  1. 使用 len() 方法
1
2
def is_empty(s):
return len(s) == 0

如果 len(s) 返回 0,则表示集合为空。

  1. 使用 not 关键字
1
2
def is_empty(s):
return not s

如果集合为空,not s 返回 True,否则返回 False。

  1. 使用 bool() 方法
1
2
def is_empty(s):
return bool(s) == False

bool(s) 将集合转换为布尔值,如果为空集合,返回 False,否则返回 True。

  1. 与空集合进行比较
1
2
def is_empty(s):
return s == set()

如果集合 s 与空集合相等,则 s 也为空集合。

总之,判断一个 Python 集合是否为空有很多种方式,选择一个简单明了的方法即可。

(END)