python

Python set()函数的高级技巧

小樊
83
2024-08-02 08:04:18
栏目: 编程语言

  1. 使用set()函数来去除重复元素
lst = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(lst)
print(unique_set)

输出结果:

{1, 2, 3, 4, 5}
  1. 使用集合运算符进行交集、并集和差集操作
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# 交集
intersection = set1 & set2
print(intersection)

# 并集
union = set1 | set2
print(union)

# 差集
difference = set1 - set2
print(difference)

输出结果:

{4, 5}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3}
  1. 使用set()函数来快速创建集合
s = set([1, 2, 3, 4, 5])
print(s)

输出结果:

{1, 2, 3, 4, 5}
  1. 使用set()函数来检查两个集合是否相等
set1 = {1, 2, 3}
set2 = {3, 2, 1}

if set1 == set2:
    print("The sets are equal")
else:
    print("The sets are not equal")

输出结果:

The sets are equal
  1. 使用set()函数来检查一个集合是否是另一个集合的子集或超集
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

if set1.issubset(set2):
    print("set1 is a subset of set2")

if set2.issuperset(set1):
    print("set2 is a superset of set1")

输出结果:

set1 is a subset of set2
set2 is a superset of set1

0
看了该问题的人还看了