一篇文章带你了解python集合基础

时间:2022-12-07 14:22:02

 

1. 集合类型定义

 

(1)集合是多个元素的无序组合

  • 集合类型与数学中的集合概念一致
  • 集合元素之间无序,每个元素唯一,不存在相同元素
  • 集合元素不可更改,不能是可变数据类型
  • 集合使用{}表示,元素间用英文逗号分隔
  • 建立集合类型用{}或set()
  • 建立空集合类型,必须使用set()
a = {"python",256,("sbvsb",251)}
print(a)

b = set("python")
print(b)

c = {"python",256,"python",256}
print(c)

 

2. 集合操作符

一篇文章带你了解python集合基础

  • 6个操作符

一篇文章带你了解python集合基础

  • 4个增强操作符

一篇文章带你了解python集合基础

 

 3. 集合处理方法

一篇文章带你了解python集合基础

 

4. 集合类型应用场景

 

(1)包含关系比较

>>>"p" in {‘p","y","t","h"}
True
>>>{‘p","y"} <= {‘p","y","t","h"}
True

 

(2)数据去重:集合数据所有元素无重复

>>>ls = [‘p","p","y","y","t","h"]
>>>s = set(ls)
{‘p","y","t","h"}
>>>ls = list(s)
[‘p","y","t","h"]

 

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/m0_55697123/article/details/119190849