几道题
1.val = 'i am a string'
a= val[::-1]
或:
a = (list(val))
a.reverse()
print(''.join(a))
2,
a = []
for i in range(101, 200):
for b in range(2, i-1):
if i % b == 0:
break
else:
a.append(i)
print(len(a))
3
*? 重复任意次,但尽可能少重复
+? 重复1次或更多次,但尽可能少重复
?? 重复0次或1次,但尽可能少重复
{n,m}? 重复n到m次,但尽可能少重复
{n,}? 重复n次以上,但尽可能少重复
4
print(v1-v2)
print(v2-v1)
print(v1 & v2)
5
a = "192.168.11.130"
def ip(value):
res = value.split('.')
s = ''
for i in res:
i = (bin(int(i)).strip('0b'))
if len(i) != 8:
i = i.zfill(8)#zfill 返回指定长度的字符串,原字符串右对齐,前面填充0
s += i
return int(s, 2) #把2进制的结果转换成10进制
c = ip(a)
print(c)
#############################################################################################################
def num():
return [lambda x: i * x for i in range(4)] #['0*x',1*x','2*x','3*x']
print([m(2) for m in num()]) # for m in num(): m(2)
结果:[6,6,6,6]
问题的本质在与python中的属性查找规则,LEGB(local,enclousing,global,bulitin),在上面的例子中,
i就是在闭包作用域(enclousing),而Python的闭包是 迟绑定 , 这意味着闭包中用到的变量的值,
是在内部函数被调用时查询得到的.
解决办法也很简单,那就是变闭包作用域为局部作用域。
def
create():
return
[
lambda
x, i
=
i:i
*
x
for
i
in
range
(
5
)]
for
i
in
create():
print
(i(
2
))
换种写法:
def
create():
a
=
[]
for
i
in
range
(
5
):
def
demo(x, i
=
i):
return
x
*
i
a.append(demo)
return
a
for
i
in
create():
print
(i(
2
))