元组
创建元组
列表是可变序列(容器),创建列表时分配的内存比实际占用的大;而元组是不可变的序列,使用元组可以节省内存。
元组创建后其元素不可修改。
# 赋值创建元组
t = ()
t1 = ('a', 'b', 'c')
t2 = 'a', 'b', 'c' # 赋值时括号可省略
# tuple实例化创建元组
t2 = tuple()
t3 = tuple(['a', 'b', 'c'])
print(t3)
元组运算
t = ('a', 'b', 'c')
print(t[0]) # 访问元组元素
color, size = 'red', 10 # 利用元组同时为多变量赋值
(color, size) = ('red', 10)
ls = ['a', 'b', 'c']
ls[0], ls[1] = ls[1], ls[0] # 利用元组交换元素
print(ls)
集合
创建集合
集合中的元素只能是不可变类型,如整数、浮点数、字符串等,不能包含列表和集合等可变类型。
# 赋值创建
set2 = {1, 2, 3}
# set实例化创建
set1 = set() # 创建空集合
set3 = set([1, 2, 3])
print(set3)
# s = {1, 2, 3, [1]} # 集合元素不能为列表,不合语法的集合
集合方法
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set1.add('a') # 添加元素,若元素已存在则不作操作
set1.discard('a') # 删除元素,若元素不在集合中不作操作
set1.remove(1) # 删除元素,若元素不在集合中抛出KeyError
set1.clear() # 清空集合
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.union(set2) # 并集
set4 = set1.intersection(set2) # 交集
set5 = set1.difference(set2) # 差集
print(set3, set4, set5)
print(set1.issubset(set1)) # 判断是否为子集
集合的高效性
管理不重复的数据时集合比列表的效率更高。
from time import time
n = 10 ** 7 # 容器中元素数量
ls = list(range(n))
t1 = time()
if n-1 in ls: # 检索特定元素是否在容器中,列表需要通过遍历的方式,用时较长
print('{} in the list ls.'.format(n-1))
t2 = time()
print('列表检索元素用时:', t2-t1)
set1 = set(range(n))
t1 = time()
if n-1 in set1: # 检索特定元素是否在容器中,集合基于哈希表的数据结构,用时较短
print('{} in the set set1.'.format(n-1))
t2 = time()
print('集合检索元素用时:', t2-t1)