python里set有哪些成功案例

   2024-10-01 6830
核心提示:去重操作:set最常见的用途就是去除列表或者其他序列中的重复元素,可以通过将序列转换为set来去除重复元素。lst = [1, 2, 2, 3,

去重操作:set最常见的用途就是去除列表或者其他序列中的重复元素,可以通过将序列转换为set来去除重复元素。

lst = [1, 2, 2, 3, 4, 4, 5]unique_set = set(lst)print(unique_set)  # 输出:{1, 2, 3, 4, 5}
集合运算:set提供了丰富的集合运算方法,比如并集、交集、差集等操作。
set1 = {1, 2, 3, 4, 5}set2 = {3, 4, 5, 6, 7}union_set = set1.union(set2)intersection_set = set1.intersection(set2)difference_set = set1.difference(set2)print(union_set)  # 输出:{1, 2, 3, 4, 5, 6, 7}print(intersection_set)  # 输出:{3, 4, 5}print(difference_set)  # 输出:{1, 2}
快速查找:set内部是使用哈希表实现的,因此可以快速进行成员检查操作。
s = {1, 2, 3, 4, 5}if 3 in s:    print("3存在于集合中")
标记重复元素:可以利用set的不可重复性质来判断是否存在重复元素。
lst = [1, 2, 2, 3, 4, 4, 5]if len(lst) == len(set(lst)):    print("列表中没有重复元素")else:    print("列表中存在重复元素")
使用set进行去重统计:可以利用set和列表推导式来统计列表中不重复元素的个数。
lst = [1, 2, 2, 3, 4, 4, 5]unique_elements_count = len({x for x in lst})print(unique_elements_count)  # 输出:5

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号