最近在等结果时,想想再学一下python吧。于是去了digy挺基础的的廖雪峰的网站开始学
从函数的参数开始学的.
后面定个小目标吧,每天一题,或者一星期七章。
下面就是我自己写的代码,不知道对不对
1.函数的参数
def product(*x):
if len(x)< 1:
raise TypeError("")
else:
y =1
for X in x:
y = y* X
return y
2.递归函数
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move((n-1), a, c, b)
print(a, '-->', c)
move((n-1), b, a, c)
3.切片
def trim(s):
p = 0
while p < len(s): # 截取到字符开始
if s[p] ==' ':
p = p + 1
else:
break
q = len(s)
while q > 0:
if s[q-1] == ' ':
q = q - 1
else:
break
return s[p:q]
4.迭代
def findMinAndMax(L):
if len(L) == 0: #如果为空字符,报错
return(none,none)
max = L[0] # 初始值
min = L[0]
for i in L:
if i > max:
max = i
if i < min:
min = i
return(min,max)
5.列表表达式
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s,str)]
print(L2)
6.生成器(杨辉三角)
def triangles():
L = [1]
while True:
yield L
L = [1] + [L[i - 1] + num for i, num in enumerate(L) if i] + [1] #组合为一个索引序列,同时列出数据和数据下标
return L
n = 0
results = []
for t in triangles():
print(t)
results.append(t)
n = n + 1
if n == 10:
break
7.map和reduce的使用
第一题
def normalize(name):
return name[0].upper() + name[1:].lower()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
第二题
from functools import reduce
def prod(L):
def fn(x,y):
return x*y
return reduce(fn,L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
第三题
from functools import reduce
digital_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
def str2float(s):
i,j = s.split('.')
left = reduce(lambda x,y:x*10+y,map(lambda x:digital_dict.get(x),i))
right = reduce(lambda x,y:x/10+y,list(map(lambda x:digital_dict.get(x),j))[::-1])/10
return left+right
str2float('123.456')
8.sorted函数
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
L2 = sorted(L, key=by_name)
print(L2)
def by_score(t):
return t[1]
L2 = sorted(L, key=by_score)
print(L2)
网友评论