python如何定义集合

原创
ithorizon 7个月前 (09-28) 阅读数 67 #Python

Python中集合(set)的定义与使用

在Python中,集合(set)是一个无序的、不重复的元素序列,它具有以下特点:

集合中的元素必须是唯一的。

集合是无序的,这意味着元素在集合中的位置不固定。

集合不能进行索引操作(如set[0])。

集合中的元素可以是任何数据类型。

定义集合的方式有两种:

1、使用大括号 {}:

s = {1, 2, 3, 4}

2、使用set()函数:

s = set([1, 2, 3, 4])

集合的常见操作包括:

添加元素使用add()方法

s.add(5)

删除元素使用remove()方法

s.remove(3)

检查元素是否在集合中使用in关键字

if 4 in s:
    print("Element is in the set")
else:
    print("Element is not in the set")

集合的并集、交集、差集使用union()、intersection()、difference()方法

s1 = {1, 2, 3}
s2 = {3, 4, 5}
print("Union:", s1.union(s2))  # {1, 2, 3, 4, 5}
print("Intersection:", s1.intersection(s2))  # {3}
print("Difference:", s1.difference(s2))  # {1, 2}


热门