
1、isdisjoint 方法用于判断两个集合是否存在相同元素,没有返回 True,否则返回 False。
1 2 3 4 5 6 7 8 9 10 11 12 13 | my_set1 = { "apple" , "orange" , "pear" , "grape" }
my_set2 = { "banana" , "watermelon" }
# 两个集合没有相同元素
ret_bool = my_set1.isdisjoint(my_set2)
print(ret_bool) # 返回 True
my_set1 = { "apple" , "orange" , "pear" , "grape" }
my_set2 = { "banana" , "watermelon" , "apple" }
# 两个集合有相同元素
ret_bool = my_set1.isdisjoint(my_set2)
print(ret_bool)
|
2、issubset 该方法用于判断一个集合是否是另一个集合的子集,确定是返回 True,否则返回 False。
1 2 3 4 5 6 7 8 9 10 11 12 13 | my_set1 = { "apple" , "orange" , "pear" , "grape" }
my_set2 = { "banana" , "watermelon" }
# 第二个集合不是第一个集合的子集
ret_bool = my_set2.issubset(my_set1)
print(ret_bool) # 返回 False
# 第二个集合是第一个集合的子集
my_set1 = { "apple" , "orange" , "pear" , "grape" }
my_set2 = { "orange" , "apple" }
ret_bool = my_set2.issubset(my_set1)
print(ret_bool) # 返回 True
|
以上就是Python判断集合的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。