对于列表,元组,集合的异同,有如下解释
#list ----> 允许重复的集合,修改# tuple ----> 允许重复的集合,不修改# set ----> 不允许重复的集合下面是示例代码:
1 s1 = set() 2 s2 = {1,2,3,4} 3 s3 = set([11,22,33,44]) 4 s4 = {3,4,5,6,89} 5 print type(s2) #<type ‘set‘> 6 s1.add(44) 7 print s1 #set([44]) 8 s1.clear() 9 print s1 #set([]) 10 print s2.difference(s4) #set([1, 2]) (s1中存在,s2中不存在的) 11 12 print s2 #set([1, 2, 3, 4]) 13 diff = s2.difference_update(s4) 14 print s2 # s1中存在,s2中不存在的,更新s1, set([1, 2]) 15 print diff 16 17 s3.discard(44) 18 print s3 19 s3.discard(55) #要移除的元素不存在时,不报错 20 print s3 21 s3.remove(66) #要移除的元素不存在时,报错 22 23 s5 = {77,88,99} 24 s6 = {88,77} 25 ret1 = s5.intersection(s6) 26 print ret1 #取交集 set([77]) 27 28 s5.intersection_update(s6) 29 print s5 #取交集,更新s5 30 ret2 = s5.isdisjoint(s6) 31 print ret2 #有交集是false 32 33 ret3 = s5.issubset(s6) 34 print ret3 #判断s5是否为s6的子序列 35 36 ret4 = s5.issuperset(s6) 37 print ret4 #判断s5是否为s6的父序列 38 39 ret5 = s6.pop() 40 print ret5 #88 41 print s6 #set([77]) 42 43 ret6 = s2.symmetric_difference(s4) 44 print ret6 #set([1, 2, 5, 6]) s2中存在的,s4不存在,+ s4存在,s2不存在 45 46 ret7 = s2.union(s4) 47 print ret7 #set([1, 2, 3, 4, 5, 6])取并集 48 49 s2.update(s4) 50 print s2 #set([1, 2, 3, 4, 5, 6, 89])并在一起
三元运算的形式:name = 值1 if 条件 else 值2
下面是普通的运算:
1 if 1 == 1 : 2 name = "alex" 3 else: 4 name = "eric"5 print name
下面是三元运算:
1 name = "alex" if 1 == 1 else "eric" 2 print name
拷贝:字符串数字,拷贝,赋值,地址深浅拷贝无意义,因为字符串的优化机制,ID都是一样的
1 import copy 2 n1 = 123 3 print id(n1) 4 n2 = n1 5 print id(n2) 6 n3 = copy.copy(n1) 7 print id(n3)
深拷贝全部拷贝,除了最内一层,浅拷贝只拷贝了最外面一层,所以K1的ID是一样的。
1 n4 = {"k1":"wu","k2":123,"k3":["alex",456]} 2 n5 = copy.copy(n4) 3 print "n4 id:" + str(id(n4)) 4 print "n5 id:" + str(id(n5)) 5 6 print id(n4[‘k1‘]) 7 print id(n5[‘k1‘]) 8 #39516400 9 #39516400
时间: 2024-10-05 04:09:25