Python集合类型

目录

目标

版本

官方文档

集合分类

实战

创建

循环

常用方法


目标

        掌握set和frozenset两种集合的使用方法,包括:创建、交集、并集、差集等操作。


版本

        Python 3.12.0


官方文档

Set Types — set, frozenseticon-default.png?t=N7T8https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset


集合分类

官方定义

Set Types — set, frozenset
    A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)

    Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

    There are currently two built-in set types, set and frozenset. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

    Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor.

译文

  1. 集合对象是无序的,因此集合不记录元素的插入位置或顺序,因此集合不支持索引、切片或其他类似序列对象的方法。
  2. 目前有两种内置的集合类型,分别是 set 和 frozenset。
  3. set是可变的,内容可以通过add()和remove()等方法进行更改。由于它是可变的,它没有哈希值,因此不能用作字典键或另一个集合的元素。
  4. frozenset是不可变的,其内容在创建后不能更改;因此可以用作字典键或另一个集合的元素。
  5. 集合用大括号或构造方法创建,用逗号分隔元素。

补充

        setfrozenset内的元素不可以重复


实战

frozenset和set的操作基本一致(构造方法名不同、frozenset不能增删元素而set能增删元素),因此这里只例举set类型的使用方法。

创建

官方文档

class set([iterable])
class frozenset([iterable])
    Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.

    Sets can be created by several means:

    Use a comma-separated list of elements within braces: {'jack', 'sjoerd'}

    Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'}

    Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo'])

译文

  1. 集合的元素来自可迭代对象。如果未指定可迭代对象,则返回一个新的空集合。
  2. 集合的元素必须是可哈希的。
  3. 集合嵌套集合,内部的集合必须是frozenset。

集合的创建方法:

  1. 用大括号创建,元素用逗号分隔。
  2. 用集合推导式创建。
  3. 用set构造方法创建。

用大括号创建,元素用逗号分隔。

mySet={"a","b","c"}
#输出:<class 'set'>
print(type(mySet))
#输出:{'b', 'c', 'a'}
print(mySet)

用集合推导式创建。

mySet={c for c in '1231231234545' if c not in '123'}
#输出:<class 'set'>
print(type(mySet))
#输出:{'4', '5'}
#分析:拆分字符串,将每个字符作为集合的元素,条件是元素不能为:1、2、3
print(mySet)

用set构造方法创建。

方法一(用list创建set)

mySet= set([1, 2, 3, 3, 4, 4, 5,False,True,None,None,"1"])
#输出:{False, 1, 2, 3, 4, 5, None, '1'}
print(mySet)

方法二(用tuple创建set)

mySet= set((1, 2, 3, 3, 4, 4, 5,False,True,None,None,"1"))
#输出:{False, 1, 2, 3, 4, 5, None, '1'}
print(mySet)

方法三(用字符串创建set)

mySet= set("1234567890123")
#输出:{'3', '0', '9', '6', '2', '8', '1', '4', '5', '7'}
print(mySet)

方法四(根据文件对象创建set)

# 我桌面有个a.txt文件
with open('C://Users//20203//Desktop//a.txt', 'r') as file:
    mySet = set(file.readlines())
# 输出:{'2\n', '4\n', '3\n', '1\n', 'True', 'False\n'}
print(mySet)

# 去掉\n
with open('C://Users//20203//Desktop//a.txt', 'r') as file:
    mySet = set(line.strip() for line in file.readlines())
print(mySet)

方法五(根据迭代器对象创建set)

myIter=iter([1,2,3,False,True,"Hello World."])
mySet=set(myIter)
#输出:<class 'set'>
print(type(mySet))
#输出:{False, 1, 2, 3, 'Hello World.'}
print(mySet)

循环

方法一(for循环)

mySet={1,2,3,4,5}
for value in mySet:
    print(value)

方法二(enumerate() 函数)

mySet={1,2,3,4,5}
for index,value in enumerate(mySet):
    print(index,value)

方法三(while循环)

mySet = {1, 2, 3, 4, 5}
#使用while循环遍历集合
iterator = iter(mySet)
while True:
    try:
        element = next(iterator)
        print(element)
    except StopIteration:
        break

常用方法

元素个数

mySet = {123, 2, 3, 4, 5}
print(len(mySet))

集合是否包含元素

mySet = {123, 2, 3, 4, 5}
#输出:True
print(2 in mySet)

集合是否不包含元素

mySet = {123, 2, 3, 4, 5}
#输出:True
print(2 not in mySet)

交集

mySet={123, 2, 3, 4, 5}
yourSet={123, 2, 3, 4, 5,6,7}
#交集
otherSet = mySet & yourSet
#输出:{2, 3, 4, 5, 123}
print( otherSet )

并集

mySet={123, 2, 3, 4, 5}
yourSet={123, 2, 3, 4, 5,6,7}
#交集
otherSet = mySet | yourSet
#输出:{2, 3, 4, 5, 6, 7, 123}
print( otherSet )

差集

mySet={123, 2, 3, 4, 5}
yourSet={123, 2, 3, 4, 5,6,7}
#差集
otherSet = yourSet - mySet
#输出:{6, 7}
print( otherSet )

对称差集

mySet={123, 2, 3, 4, 5,9}
yourSet={123, 2, 3, 4, 5,6,7}
#对称差集
otherSet = mySet ^ yourSet
#输出:{6, 7, 9}
print( otherSet )

集合嵌套集合

mySet = {frozenset(["a","b"]),frozenset(["c","d"]) }
#输出:<class 'frozenset'>
print(type(frozenset(["a"])))
for inner_set in mySet:
    print("--------")
    for element in inner_set:
        print(element)

添加元素

mySet={1, 2, 3, 4, 5}
mySet.add(6)
#输出:{1, 2, 3, 4, 5, 6}
print(mySet)

删除元素

mySet={1, 2, 3, 4, 5}
mySet.remove(1)
#输出:{2, 3, 4, 5}
print(mySet)

是否没有共同元素

mySet = {1, 2, 3, 4, 5}
yourSet = {1, 2, 3}
# 输出:False
# 分析:有共同元素:1,2,3
print(mySet.isdisjoint(yourSet))

mySet = {4, 5}
yourSet = {1, 2, 3}
# 输出:True
# 分析:没有共同元素
print(mySet.isdisjoint(yourSet))

是否是子集关系

mySet = {1, 2, 3, 4, 5}
yourSet = {1, 2, 3}
# 输出:False
# 分析:mySet不是yourSet的子集
print(mySet.issubset(yourSet))
# 输出:True
# 分析:yourSet是mySet的子集
print(yourSet.issubset(mySet))

是否是超集关系

mySet = {1, 2, 3, 4, 5}
yourSet = {1, 2, 3}
# 输出:True
# 分析:mySet是yourSet的超集
print(mySet.issuperset(yourSet))
# 输出:False
# 分析:yourSet不是mySet的超集
print(yourSet.issuperset(mySet))

  • 21
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值