Python中的set是一个无序且不重复的元素集合,支持交集、并集、差集等操作。创建set使用大括号{}set()函数。

在Python中,set函数用于创建一个无序且不重复的元素集合,它可以接受一个可迭代对象(如表、元组、字符串等)作为参数,并返回一个集合对象。

以下是关于set函数的详细解释和使用示例:

python中set的用法python中set的用法

1、创建空集合:

“`python

empty_set = set()

print(empty_set) # 输出: set()

“`

2、创建包含元素的集合:

“`python

my_set = {1, 2, 3}

print(my_set) # 输出: {1, 2, 3}

“`

3、使用set函数将列表转换为集合:

“`python

my_list = [1, 2, 3, 2, 4]

my_set = set(my_list)

print(my_set) # 输出: {1, 2, 3, 4}

“`

4、使用set函数将字符串转换为集合:

“`python

python中set的用法python中set的用法

my_string = "hello"

my_set = set(my_string)

print(my_set) # 输出: {‘h’, ‘e’, ‘l’, ‘o’}

“`

5、添加元素到集合:

“`python

my_set = {1, 2, 3}

my_set.add(4)

print(my_set) # 输出: {1, 2, 3, 4}

“`

6、删除集合中的元素:

“`python

my_set = {1, 2, 3}

my_set.remove(2)

print(my_set) # 输出: {1, 3}

“`

7、判断元素是否在集合中:

“`python

python中set的用法python中set的用法

my_set = {1, 2, 3}

print(2 in my_set) # 输出: True

print(4 in my_set) # 输出: False

“`

8、求两个集合的交集:

“`python

set1 = {1, 2, 3}

set2 = {2, 3, 4}

print(set1 & set2) # 输出: {2, 3}

“`

9、求两个集合的并集:

“`python

set1 = {1, 2, 3}

set2 = {2, 3, 4}

print(set1 | set2) # 输出: {1, 2, 3, 4}

“`

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。