Python中的set()函数:去重方法详解
发布时间:2023-05-28 00:18:16
在Python中,可以使用set()函数来去重。set()函数是一个内置函数,可以将列表或字符串等序列类型转换为集合类型,并自动去重。
下面我们来详细了解一下set()函数的用法:
1. 将列表转换为集合并去重
使用set()函数将列表转换为集合类型,并可自动去重。例如:
lst = [2, 3, 4, 2, 1, 5, 3] new_lst = set(lst) print(new_lst)
输出结果为:{1, 2, 3, 4, 5}
2. 将字符串转换为集合并去重
使用set()函数将字符串转换为集合类型,并可自动去重。例如:
str = 'hello world' new_str = set(str) print(new_str)
输出结果为:{'d', 'e', 'h', ' ', 'w', 'l', 'r', 'o'}
注意:在Python中,字符串是不可变类型。
3. 添加元素到集合中
使用add()函数向集合中添加元素。例如:
new_lst.add(6) print(new_lst)
输出结果为:{1, 2, 3, 4, 5, 6}
4. 删除集合中的元素
使用remove()函数从集合中删除指定元素。例如:
new_lst.remove(1) print(new_lst)
输出结果为:{2, 3, 4, 5, 6}
5. 更新集合中的元素
使用update()函数更新集合中的元素。例如:
new_lst.update([4, 9]) print(new_lst)
输出结果为:{2, 3, 4, 5, 6, 9}
6. 求两个集合的交集
使用&运算符或intersection()函数求两个集合的交集。例如:
set1 = {1, 2, 3, 4}
set2 = {2, 3, 4, 5}
print(set1 & set2)
print(set1.intersection(set2))
输出结果为:{2, 3, 4}
7. 求两个集合的并集
使用|运算符或union()函数求两个集合的并集。例如:
print(set1 | set2) print(set1.union(set2))
输出结果为:{1, 2, 3, 4, 5}
8. 求两个集合的差集
使用-运算符或difference()函数求两个集合的差集。例如:
print(set1 - set2) print(set1.difference(set2))
输出结果为:{1}
set()函数是一个非常方便的去重方法,在Python编程中用到的频率较高,希望本文能对大家的Python编程有所帮助。
