一 深浅拷贝
浅拷贝只能拷贝最外层,修改内层则原列表和新列表都会变化。
深拷贝是指将原列表完全克隆一份新的。
二 列表推导式
# 列表推倒式
li = [1,2,3,4,5,6,7,8,9]
print([x**2 for x in li])
# 输出:[1, 4, 9, 16, 25, 36, 49, 64, 81]
print([x**2 for x in li if x>5])
# 输出:[36, 49, 64, 81]
result = dict([x,x*10] for x in li)
print(result)
# 输出:{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}
result = [(x,y) for x in range(10) if x%2 if x>3 for y in range(10) if y>7 if y != 8]
# 上面的 x%2 表示的是 x%2 != 0
print(result)
# 输出:[(5, 9), (7, 9), (9, 9)]
content = [2,4,6]
content2 = [4,3,-9]
sq = [content[i] + content2[i] for i in range(len(content))]
print(sq)
# 输出:[6,7-3]
print([x*y for x in [1,2,3] for y in [1,2,3]])
# 输出:[1, 2, 3, 2, 4, 6, 3, 6, 9]
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = [a for a in list_a for b in list_b if a == b]
print(common_num)
# 输出:[2,3,4]
三 zip 的简单用法
zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回这些由元组组成的对象,
我们可以使用list()来转换输出的列表, 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,
利用*号操作符,可以将元组解压为列表
# zip 必须加list()
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)
print(zipped)
# 输出:<zip object at 0x0066E440>
e = list(zipped)
print(e)
# 输出:[(1, 4), (2, 5), (3, 6)]
f = list(zip(a,c))
print(f)
# 输出:[(1, 4), (2, 5), (3, 6)]
# zip 与字典的结合
x = ['a','b','c']
y = ['x','y','z']
z = zip(x,y)
#print(list(z))
# 输出:[('a','x'),('b','y'),('c','z')]
d = dict(z)
#print(d)
# 输出:{'a': 'x', 'c': 'z', 'b': 'y'}
# zip的压缩与解压
x = [1,2,3]
y = [4,5,6]
z = [7,8,9]
xyz = zip(x,y,z)
print(list(xyz))
# 输出:[(1,4,7),(2,5,8),(3,6,9)] 同上
xyz = zip(x,y,z)
res = zip(*xyz)
#print(list(res))
res = zip(*zip(x,y,z)) # 这个是上面三行代码的和写
print(list(res))
# 输出:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
a1,a2 = zip(*zip(x,y))
print(list(a1))
# 输出:[1,2,3]
关于zip的简单题目
x = [1,2,3]
z = x * 3
#print(z)
# 输出:[1,2,3,1,2,3,1,2,3]
z = list(x) * 3
print(z)
# 输出:[1,2,3,1,2,3,1,2,3]
print([x])
# 输出:[[1,2,3]]
# 所以才有下面的:
z = [x] * 3
print(z)
#输出:[[1,2,3],[1,2,3],[1,2,3]]
r = zip(* [x]*3)
#print(list(r))
# 输出:[(1, 1, 1), (2, 2, 2), (3, 3, 3)]