欢迎访问宙启技术站
智能推送

Python中set()函数使用示例:快速去重和数学集合运算

发布时间:2023-07-01 13:52:14

在Python中,set()函数是用来创建一个集合对象的。集合是一种无序的、不重复的元素集合,可以快速的对元素进行去重操作,同时还可以进行数学集合运算。

下面是set()函数的使用示例:

1. 创建一个空集合:

my_set = set()
print(my_set)  # 输出 set()

2. 创建一个带有元素的集合:

my_set = set([1, 2, 3, 4, 5])
print(my_set)  # 输出 {1, 2, 3, 4, 5}

3. 对列表进行去重:

my_list = [1, 2, 3, 4, 3, 2, 1]
my_set = set(my_list)
print(my_set)  # 输出 {1, 2, 3, 4}

4. 对字符串进行去重:

my_str = "hello"
my_set = set(my_str)
print(my_set)  # 输出 {'h', 'l', 'o', 'e'}

5. 使用in关键字判断元素是否存在于集合中:

my_set = set([1, 2, 3, 4, 5])
if 3 in my_set:
    print("3存在于集合中")
else:
    print("3不存在于集合中")

6. 集合的数学运算:并集、交集、差集和对称差集。

set1 = set([1, 2, 3, 4, 5])
set2 = set([4, 5, 6, 7, 8])

# 并集
union_set = set1.union(set2)
print(union_set)  # 输出 {1, 2, 3, 4, 5, 6, 7, 8}

# 交集
intersection_set = set1.intersection(set2)
print(intersection_set)  # 输出 {4, 5}

# 差集
difference_set = set1.difference(set2)
print(difference_set)  # 输出 {1, 2, 3}

# 对称差集
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)  # 输出 {1, 2, 3, 6, 7, 8}

以上是set()函数在Python中的使用示例。通过set()函数,我们可以快速的对列表或字符串进行去重操作,同时还可以进行数学集合运算,方便的完成集合相关的操作。