# 带你认识优秀的python代码

names = "LI XIA , ZHAO MING ,LAO WANG *,DA XIONG >,LI MEI MEI,"\ "CHANG JIANG,LI QIANG,ZHANG WU JI,ZHANG SAN FENG,"\ "DU GU QIU BAI,QIAO FENG" def problems7(names): newnames =[name.title().strip('*>') for name in names.split(',')] names_dict = {name:len(name) for name in newnames} result = sorted(names_dict.items(),key=lambda x:x[1],reverse=True) print(result) problems7(names)

[('Zhang San Feng', 14), ('Du Gu Qiu Bai', 13), (' Zhao Ming ', 11), ('Chang Jiang', 11), ('Zhang Wu Ji', 11), ('Li Mei Mei', 10), ('Lao Wang ', 9), ('Da Xiong ', 9), ('Qiao Feng', 9), ('Li Qiang', 8), ('Li Xia ', 7)]

1.strip函数

2.split函数

1.简洁的表达式，比如if/else放在一行里面

def test(m):return 'a' if m==1 else 'b'

2.构成一个字典序列

print(dict(zip('abcd',range(4)))) >>{'a':0, 'c':2, 'b':1,'d':3}

3.if else print一行搞定

print('ok' if a==1 else 'ko')

4.一行代码，巧妙的求解：列出1到20的数字，若是3的倍数就用apple代替，若是5的倍数就用orange代替，若既是3的倍数又是5的倍数就用appleorange代替。

print(['apple'[i%35::]+'orange'[i%56::] or i for i in range(1,21)])

69 篇文章11 人订阅

0 条评论