3、s = [1, "h", 2, "e", [1, 2, 3], "l", (4, 5), "l", {1: "111"}, "o"], 将s中的5个字符提取出来并拼接成字符串。
s = [1, "h", 2, "e", [1, 2, 3], "l", (4, 5), "l", {1: "111"}, "o"]
print("".join([i for i in s if isinstance(i, str)])) # hello
6.浅拷贝
a = [1, 2, [3, "hello"], {"egon": "aigan"}]
b = a[:] # 此时发生了一个浅拷贝,嵌套列表的 内存地址是相同的
a[0] = 5
a[2][0] = 6666
print(a) # [5, 2, [6666, 'hello'], {'egon': 'aigan'}]
print(b) # [1, 2, [6666, 'hello'], {'egon': 'aigan'}]
11.用str.center打印菱形
# *
# ***
# *****
# *******
# *****
# ***
# *
def draw(n):
for i in range(1,n,2):
print(("*"*i).center(n))
for i in range(n,0,-2):
print(("*"*i).center(n))
draw(*)
12.nonlocal 往外包一层
def outer():
count = 10
def inner():
nonlocal count
count = 20
print(count)
inner()
print(count)
outer()
思考题
# 思考题
# 有如下类,请重写方法判断,只要name和sex相同我们就认为是一个对象
class Person:
def __init__(self,name,age,sex,weight):
self.name = name
self.sex = sex
self.age = age
self.weight = weight
def __eq__(self, obj):
if self.name == obj.name and self.sex == obj.sex:
return True
def __hash__(self):
return (self.name, self.sex).__hash__()
a1 = Person("alex", 18, "male", 60)
a2 = Person("alex", 30, "male", 60)
a2 = Person("alex1", 30, "male", 60)
s = set([a1,a2])
print(s)