Python的集合

昨天重新学习了Python的集合set。

# 21080723
#http://www.liujiangblog.com/course/python/24
#集合 set

s = set([1,2,3,4,4])
print(s)     #自动去重复
#运行结果: {1, 2, 3, 4}

#知识点:
#set集合,使用花括号框定元素,并以逗号区分元素。
#创建集合使用set(),而非{},后者为创建字典。
#set 是一个无序无重复的集合。


s1= set("it is a nice day")
print(s1)
#第一次运行结果:{'n', 'a', 'i', 's', ' ', 'e', 't', 'y', 'd', 'c'}
#第二次运行结果:{'e', 's', 'c', 'i', 't', 'n', ' ', 'd', 'y', 'a'}
#每次运行出来的结果都不同,因为set是一个无序无重复的集合。
#这就意味着每次它返回元素的顺序都是不固定的。

b = set([1])
print(b.add(5))
#为什么不能添加元素到set里呢?
#运行结果为:None

num_set = {1, 2, 3, 4, 5}
word_set = set(["one","two","three"])
print(word_set)
#运行结果: {'one', 'two', 'three'}

print(3 in num_set)
#result: True
print("two" in word_set)
#result: True


for ele in word_set:
	print(ele)
#这个结果会发生变化,虽然还是每个元素都遍历,但是没有顺序,每次遍历的顺序都不同。
#result 1: one two three
#result 2:  one three two


b = set([1])
b.add(2)   # add()方法会在集合里添加一个元素,但是它不会返回新的列表,而会返回none,返回none则说明是添加成功了。
print(b)    # 如果想要看一下添加成功后的集合,只需再次查看该集合即可。
#为什么不能添加元素到set里呢
#运行结果为:None
#参考: https://stackoverflow.com/questions/9299919/add-number-to-set
#对于可变序列的变化操作,如删除,添加,返回的结果都是none,要查看结果,需要再次打印出原可变序列。
#(其实他们都悄悄改变了)。
#有类似性质的还有 list.sort()
list = [1,3,2]
print(sorted(list))
#sorted()和sort()的不同就在这里了吧。第一本python书上说,sorted 是临时排序。sort是永久排序。不过我也没有弄清
#具体有什么区别。
#sorted()是python 2.4后新加的一个内建函数。
#用法如上: sorted(list), 它会将list排序,然后返回一个新的排号序的列表。
#而sort() 是作为方法使用。它只会给列表排序,但是不会重新返回一个列表,需要再次print原列表,才能查看排序结果。
#list.sort()


thisset = set(["google", "Taobao"])
print(thisset.add("facebook"))
#返回:None
#查看新集合:
print(thisset)
#运行结果:{'Taobao', 'google', 'facebook'}

#用循环迭代的方式访问集合
for word in thisset:
	print(word)

print(type(thisset))
# @<class 'set'>

color = ["red","blue"]
print(type(color))
# @<class 'list'>

a = "{0} {1}{2}".format("hello","world","!")
print(a)
# @ hello world!

#创建集合
#方法一
numbers = {21,11,42,29,22,71,18}
#方法二: 用list创建集合
colors = ["green","red","blue"]
# @<class 'list'>
colors_set = set(colors)
print(colors_set)
#@ {'red', 'green', 'blue'}  <class 'set'>

z = set([1,3,1,3])    #[1,3]是个列表,set([list])将列表转化为集合,可以去处重复。
print(z)
#@ {1, 3}    #自动去重复。
print(type(z))
#@ <class 'set'>

#用in 和 not in 判断元素是否在集合里。
print("green"in colors_set)
#@ True
print("green" not in colors_set)
#@ False

# 使用内置函数访问集合。
numbers = {21,11,42,29,22,71,18}
print(len(numbers))
# @ 7
print(min(numbers))
# @ 11
print(max(numbers))
#@ 71
print(sum(numbers))
#@ 214
print(sorted(numbers))   # set 可以用sorted直接转化为一个排序的列表。(这个好强大)。
#@ [11, 18, 21, 22, 29, 42, 71]
#sort 好像不能实现对集合的排序

# 添加新元素到集合
#集合使用 add 添加元素到当前集合,
# 使用 update 方法添加一个或多个集合到当前集合
words = {"spring","table", "cup", "bottle", "coin"}
words.add("water")    #集合使用 add 添加元素到当前集合
print(words)
#@ {'bottle', 'table', 'water', 'spring', 'cup', 'coin'}
words2 = {"apple", "pear"}
words3 = {"iPhone","Mac", "iPad"}
words.update(words2,words3)   # 使用 update 方法添加一个或多个集合到当前集合
print(words)
#@ {'spring', 'iPhone', 'bottle', 'coin', 'Mac', 'iPad', 'cup', 'water', 'pear', 'table', 'apple'}

#删除集合里的元素
#有两个删除列表元素的方法: remove() 和 discard(). remove() 删除元素时,如果元素不在集合里,
#会抛出异常, discard() 删除元素时,如果元素不在集合里,则什么也不做

words.discard("water")
words.discard("bottle")
print(words)
#@ {'table', 'spring', 'apple', 'Mac', 'coin', 'iPad', 'cup', 'pear', 'iPhone'}
words.remove("iPhone")
print(words)
#@ {'cup', 'coin', 'spring', 'iPad', 'apple', 'Mac', 'table', 'pear'}

# words.remove("hello")   #元素不再集合里时,会抛出异常 KeyError
#@ KeyError: 'hello'
#所以廖雪峰才会说集合set是没有value的字典。

try:
	words.remove("hello")
except KeyError as e:
	pass
print(words)

#集合pop与清空
#pop()删除并返回任意元素
#clear()删除集合里所有的元素。

print(words.pop())   #每次删除的元素都不同,因为这个是无序可变的set
#@1 table
#@2 iPad
#@3 pear

words.clear()

#clear 和 add, update, discard, remove 这些方法都一样,需要再次查看原序列,才知道更新状况。
# sorted 和 pop这两个方法,比较特别,可以直接返回跟新后的情况。
#不过pop返回的不是集合序列,而只是pop出去的单个元素。

# 集合的并集,交集,补集
set1 = {'a', 'b', 'c','c','d'}
set2 = {'a', 'b', 'x','y','z'}
print("intersection:", set1.intersection(set2))   #set1 和 set2 的交集
#@ intersection: {'a', 'b'}
print("union:", set1.union(set2))  #set1 和 set2 的合集
#@ union: {'b', 'd', 'c', 'a', 'y', 'x', 'z'}
print('difference:', set1.difference(set2)) #set1 和 set2 的合集差集
#@ difference: {'d', 'c'}  #set1 中不同于set2的元素。
print('difference:', set2.difference(set1)) #set1 和 set2 的合集差集
#@ difference: {'z', 'y', 'x'}  #set2 中不同于set1的元素。
print("symmetric difference:",set1.symmetric_difference(set2))  #非交集的所有元素
#@ symmetric difference: {'d', 'x', 'z', 'y', 'c'}

#用符号表示以上集合操作
print("intersection:", set1 & set2) #&与
print("union", set1 | set2)  # |或
print("difference:", set1 - set2)  # - 非
print("symmetric difference:", set1 ^ set2)  # ^异或(非交集)
#输出结果同上

# 子集与超子集的判断方法
set_a = {'a','b','c','d','e'}
set_b = {'a','b','c'}
set_c= {'x','y','z'}

if set_b.issubset(set_a):    #判断set_b是否是set_a的子集
	print("set_a is a subset of set_b")
#@ set_a is a subset of set_b

if set_a.issuperset(set_b):  # 判断set_a是否是set_b的超集
	print("set_a is a superset of set_b")
else:
	print("no")
#@ set_a is a superset of set_b    注意 super 不要写成supper了

if set_a.isdisjoint(set_c):  #判断 两个集合中是否有共同元素
	print("set_b and set_c have no common elements")
#@ set_b and set_c have no common elements

#9 使用frozenset()创建不可变set

frozen_set = frozenset(('hello','world'))
#print(frozen_set)
#@ frozenset({'world', 'hello'})    #这个返回的值,居然自带frozenset
# frozen_set.pop()   # forzenset()创建了不可变的集合,不可添元素,否则会抛出异常
print(frozen_set)
# AttributeError: 'frozenset' object has no attribute 'add'
# AttributeError: 'frozenset' object has no attribute 'remove'
# AttributeError: 'frozenset' object has no attribute 'discard'
# AttributeError: 'frozenset' object has no attribute 'pop'

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值