python入门——集合

集合

1. 作用

2. 定义

3. 类型转换

4. 内置方法

  4.1 取交集

  4.2 取并集/合集

  4.3 取差集

  4.4 对称差集

  4.5 父子集

  4.6 长度

  4.7 成员运算in notin

  4.8 循环

  4.9 discard

  4.10 update

  4.11 pop

  4.12 add

  4.13 isdisjoint

  4.14 difference_update

===========================================================================================================================

1. 作用

  去除重复的值(去重)

2. 定义

  在{}内用逗号分隔开多个元素,多个元素满足以下三个条件:1. 集合内元素必须为不可变类型2. 集合内元素无序3. 集合内元素没有重复

s={1,2} # s=set({1,2})

# s={1,[1,2]} # 集合内元素必须为不可变类型  报错
# s={1,'a','z','b',4,7} # 集合内元素无序 报错
# s={1,1,1,1,1,1,'a','b'} # 集合内元素没有重复 报错
print(s)

  s={}这个是默认为空字典 所以要s=set()

3. 类型转换

set({1,2,3})
res=set('hellolllll')
print(res)

print(set([1,1,1,1,1,1]))
print(set([1,1,1,1,1,1,[11,222]]) # 报错

print(set({'k1':1,'k2':2}))

4. 内置方法

  4.1 取交集:两者共同的好友

friends1 = {"zero","kevin","jason","egon"}
friends2 = {"Jy","ricky","jason","egon"}
res=friends1 & friends2
print(res)
print(friends1.intersection(friends2))

# {'egon', 'jason'}
# {'egon', 'jason'}

  4.2 取并集/合集:两者所有的好友

friends1 = {"zero","kevin","jason","egon"}
friends2 = {"Jy","ricky","jason","egon"}
print(friends1 | friends2)
print(friends1.union(friends2))

# {'ricky', 'Jy', 'kevin', 'jason', 'zero', 'egon'}
# {'ricky', 'Jy', 'kevin', 'jason', 'zero', 'egon'}

  4.3 取差集:取某个人独有的好友

friends1 = {"zero","kevin","jason","egon"}
friends2 = {"Jy","ricky","jason","egon"}

# 取friends1独有的好友
print(friends1 - friends2)
print(friends1.difference(friends2))
# {'zero', 'kevin'}
# {'zero', 'kevin'}

# 取friends2独有的好友
print(friends2 - friends1)
print(friends2.difference(friends1))
# {'Jy', 'ricky'}
# {'Jy', 'ricky'}

  4.4 对称差集:求两个用户独有的好友们(即去掉共有的好友)

friends1 = {"zero","kevin","jason","egon"}
friends2 = {"Jy","ricky","jason","egon"}
print(friends1 ^ friends2)
print(friends1.symmetric_difference(friends2))

# {'ricky', 'kevin', 'zero', 'Jy'}
# {'ricky', 'kevin', 'zero', 'Jy'}

  4.5 父子集:包含的关系

s1={1,2,3}
s2={1,2,4}
# 不存在包含关系,下面比较均为False
print(s1 > s2) # False
print(s1 < s2) # False

s1={1,2,3}
s2={1,2}
print(s1 > s2) # 当s1大于或等于s2时,才能说是s1是s2他爹 True
print(s1.issuperset(s2)) # True
print(s2.issubset(s1)) # s2 < s2  =>True

s1={1,2,3}
s2={1,2,3}
print(s1 == s2) # s1与s2互为父子
print(s1.issuperset(s2)) # True
print(s2.issuperset(s1)) # True

  4.6 长度

   >>> s={'a','b','c'}

   >>> len(s)

  4.7 成员运算in    not in

   >>> 'c' in s

   True

  4.8 循环

   >>> for item in s:
   ... print(item)
   ...
   c
   a
   b
   '''

  4.9 discard   remove

s={1,2,3}
s.discard(4) # 删除元素不存在do nothing
                  #{1, 2, 3}
print(s)
s.remove(4) # 删除元素不存在则报错

  4.10 update

s={1,2,3}
s.update({1,3,5})
print(s)
# {1, 2, 3, 5}

  4.11 pop

s={1,2,3}
res=s.pop()
print(res)
# 1

  4.12 add

s={1,2,3}
s.add(4)
print(s)
# {1, 2, 3, 4}

  4.13 isdisjoint

res=s.isdisjoint({3,4,5,6}) # 两个集合完全独立、没有共同部分,返回True
print(res)
# False

  4.14 difference_update

s.difference_update({3,4,5}) # s=s.difference({3,4,5})
print(s)
# {1, 2}
原文地址:https://www.cnblogs.com/liuxinging/p/12482275.html