当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Set issubset()用法及代码示例


设置 issubset() 方法

issubset() 方法用于检查这个集合(set1)是否是 set2 的子集,以 set1 和 set2 调用的方法作为参数提供,该方法返回 "True" 是 set2 中存在的 set1 的所有元素,否则该方法返回"False"。

用法:

    set1.issubset(set2)

参数:

  • set1– 它代表了 set1(这个 set)。
  • set2– 它代表 set2(另一个要比较的集合)。

返回值:

这个方法的返回类型是<class 'bool'>,它返回一个布尔值(真或假)。

范例1:

# Python Set issubset() Method with Example

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}
cars_3 = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}

# issubset() method call
result = cars_1.issubset(cars_2)
print("cars_1.issubset(cars_2):", result)

result = cars_2.issubset(cars_3)
print("cars_2.issubset(cars_3):", result)

result = cars_1.issubset(cars_3)
print("cars_1.issubset(cars_3):", result)

# checking using condition
if cars_1.issubset(cars_2):
    print("cars_1 is subest of cars_2")
else:
    print("cars_1 is not subest of cars_2")

if cars_2.issubset(cars_3):
    print("cars_2 is subest of cars_3")
else:
    print("cars_2 is not subest of cars_3")

if cars_1.issubset(cars_3):
    print("cars_1 is subest of cars_3")
else:
    print("cars_1 is not subest of cars_3")

输出

cars_1.issubset(cars_2): False
cars_2.issubset(cars_3): True
cars_1.issubset(cars_3): True
cars_1 is not subest of cars_2
cars_2 is subest of cars_3
cars_1 is subest of cars_3

范例2:

# Python Set issubset() Method with Example

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "UVW"}

# issubset() method calls
result = x.issubset(y)
print("x.issubset(y):", result)

result = y.issubset(z)
print("y.issubset(z):", result)

result = z.issubset(x)
print("z.issubset(x):", result)

result = x.issubset(z)
print("x.issubset(z):", result)

result = y.issubset(x)
print("y.issubset(x):", result)

输出

x.issubset(y): True
y.issubset(z): False
z.issubset(x): False
x.issubset(z): False
y.issubset(x): True


相关用法


注:本文由纯净天空筛选整理自 Python Set issubset() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。