赛博红兔的科技博客

CyberHongTu shares news, insights, and musings on fascinating technology subjects.


和我一起玩Python:11. 元组和集合


今天咱们来聊聊元组和集合。元组就是一堆固定的、有顺序的、不能改的元素。比如坐标啊(x, y)或者用户信息(名字、年龄、性别)这样的。想弄个元组,可以用tuple()函数,或者把一堆元素扔进小括号里。元组可以变成列表,改改再变回元组。元组加元组也是可以的,就是说要加东西进去,得先弄个新元组,再加到原来的上面。想整个删掉元组,用del命令就行。元组里没有加东西、删东西这些方法,但是能数一数有几个啥,或者某个东西在第几位。拆包的话,就是把元组里的值赋给几个变量。

集合呢,就是一堆不按顺序、每个都不一样的元素。用它可以快速查查看某个元素在不在集合里。集合支持那些数学上的集合操作,比如交集、并集、差集这些。弄个集合,可以用set()函数,或者把一堆元素扔进大括号里。集合能去重。用in和not in来查成员比在列表里快,因为集合的结构优化得不错。集合自己有一些独特的方法,比如找交集、差集、并集。

set Method List

MethodDescription
add()Adds an element to the set
clear()Removes all the elements from the set
copy()Returns a copy of the set
difference()Returns a set containing the difference between two or more sets
difference_update()Removes the items in this set that are also included in another, specified set
discard()Remove the specified item
intersection()Returns a set, that is the intersection of two other sets
intersection_update()Removes the items in this set that are not present in other, specified set(s)
isdisjoint()Returns whether two sets have a intersection or not
issubset()Returns whether another set contains this set or not
issuperset()Returns whether this set contains another set or not
pop()Removes an element from the set
remove()Removes the specified element
symmetric_difference()Returns a set with the symmetric differences of two sets
symmetric_difference_update()inserts the symmetric differences from this set and another
union()Return a set containing the union of sets
update()Update the set with the union of this set and others

集合的方法列表

方法描述
add()向集合添加元素
clear()删除集合中的所有元素
copy()返回集合的副本
difference()返回两个或多个集合的差集的集合
difference_update()删除集合中也在另一个指定集合中的项目
discard()删除指定的项目
intersection()返回两个其他集合的交集的集合
intersection_update()删除集合中不在其他指定集合(s)中的项目
isdisjoint()返回两个集合是否有交集
issubset()返回另一个集合是否包含此集合
issuperset()返回此集合是否包含另一个集合
pop()从集合中删除元素
remove()删除指定的元素
symmetric_difference()返回两个集合的对称差集的集合
symmetric_difference_update()插入此集合和另一个的对称差异
union()返回包含集合的并集的集合
update()使用此集合和其他集合的并集更新集合


Leave a comment