集合是一个无序不重复元素的集,基本功能包括关系测试和消除重复元素,结合对象还支持union(联合) intersection(交) difference(差) sysmmerric difference(对称差集)等数学运算
大括号或set()函数可以用来创建集合,注意:想要创建空集合,你必须使用set()而不是{},{}用于创建空字典
集合的创建演示如下:
# 用大括号{}来创建集合
a = {"hello","hao","hello","hao","Tom"}print(a)
结果: 它的输出结果不会重复排序每次也不一样
{'Tom', 'hello', 'hao'}
# set来创建集合
b = set(["hello","hao","hello","hao"])
print(b)
结果:
{'hao', 'hello'}
# union 联合
print(a|b)
结果:
{'hello', 'hao', 'Tom'}
# intersection 交集
print(a&b)
# sysmmetric difference 对称差集等数学运算
print(a-b)
推导式:是Python中很强大的,很受欢迎的特性,具有语言简洁,速度快等优点
1.列表推导式
2.字典推导式
3.集合推导式
# 例1; 整除3的数字列表
numders = []
for i in range(100):
if i % 3 == 0:
numders.append(i)
print(numders)
# 推导式实现
numders = [x for x in range(100)if x % 3 == 0]
print(numders)
# 输出1-10的平方 推导式
pf = [x*x for x in range(1,11)]
print(pf)
# 将单词长度大于三的转为大写输出 推导式
names = ['ton','bob','hello','jerry','wendy','look','one']
name = [x.upper() for x in names if len(x)>3]
print(name)
# 求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元组列表
aa = [(x,y) for x in range(6) if x % 2 == 0 for y in range(6) if y % 2 == 1]
print(aa)
# 求m3,6,9组成的列表
m = [[1,2,3],[4,5,6],[7,8,9]]
mm = [x for x in m for i in x if i(len(2))]
# pri求m中3,6,9组成的列表nt(mm)
print([x[2] for x in m])
#求m中斜线1,5,9组成的列表
m = [[1,2,3],[4,5,6],[7,8,9]]
print([m[x][x] for x in range(len(m))])
# 求m,n中矩阵和元素的乘积
m = [[1,2,3],[4,5,6],[7,8,9]]
n = [[2,2,2],[3,3,3],[4,4,4]]
nn = [[m[x][y]*n[x][y] for y in range(len(n))] for x in range(len(m))]
print(nn)
# 结合两个列表的元素,如果元素之间不相等的话
comds = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
comds.append((x,y))
n = [1,2,3]
m = [3,1,4]
comds = [(x,y) for x in n for y in m if x != y ]
print(comds)
# 快速更换key和value
mcase = {'a': 10 ,'b': 34}
b = {n:m for m,n in mcase.items()}
print(b)
# set集合推导
squared = {x**2 for x in [1,1,2]}
print(squared)