1. 元组
>>> a = (1,2,3,4,5) >>> b = list(a) #转换成列表对象, 可以更改 >>> b [1, 2, 3, 4, 5] >>> b[0] = "HAHA" #更新列表内的值. >>> b [‘HAHA‘, 2, 3, 4, 5] >>> c = tuple(b) #tuple,把列表转换成元组 >>> c (‘HAHA‘, 2, 3, 4, 5)
2. 集合
>>> a = set(‘abc‘) #定义集合 >>> a set([‘a‘, ‘c‘, ‘b‘]) >>> a.add(‘young‘) #增加成员 >>> a set([‘a‘, ‘c‘, ‘b‘, ‘young‘]) >>> a.update(‘TEST‘) #更新成员 >>> a set([‘a‘, ‘c‘, ‘b‘, ‘E‘, ‘young‘, ‘S‘, ‘T‘]) >>> a.remove(‘E‘) >>> a set([‘a‘, ‘c‘, ‘b‘, ‘young‘, ‘S‘, ‘T‘]) >>> a.update("TTTT") #没有重复 >>> a set([‘a‘, ‘c‘, ‘b‘, ‘young‘, ‘S‘, ‘T‘]) >>> a.update("SB") >>> a set([‘a‘, ‘c‘, ‘b‘, ‘young‘, ‘S‘, ‘B‘, ‘T‘]) >>> a.remove(‘S‘) #移除成员 >>> a set([‘a‘, ‘c‘, ‘b‘, ‘young‘, ‘B‘, ‘T‘])
>>> b = frozenset(‘abc‘) >>> b frozenset([‘a‘, ‘c‘, ‘b‘]) >>> b.add(‘a‘) Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> b.add(‘a‘) AttributeError: ‘frozenset‘ object has no attribute ‘add‘
#成员关系 >>> a set([‘a‘, ‘c‘, ‘b‘, ‘young‘, ‘B‘, ‘T‘]) >>> "a" in a True >>> "d" not in a True
#集合交集,并集,差集 >>> a = set(‘abc‘) >>> b = set(‘cde‘) >>> a & b #交集 set([‘c‘]) >>> a | b #并集 set([‘a‘, ‘c‘, ‘b‘, ‘e‘, ‘d‘]) >>> a - b #差集 set([‘a‘, ‘b‘])
#列表去重复的值 >>> a = [1,2,3] >>> a.append(2) >>> a.append(3) >>> a [1, 2, 3, 2, 3] >>> set(a) #转换成集合 set([1, 2, 3]) >>> list(set(a)) #转换成列表 [1, 2, 3]
时间: 2024-10-25 18:58:07