Python小技巧
代码运行 jupyter notebook
快速构成一个字典序列
dict(zip('abcd',range(4)))
>>>{'a': 0, 'b': 1, 'c': 2, 'd': 3}
用类似三目运算输出
a =1
"11" if a==1 else "22"
>>>'11'
直接return 条件判断
def test(a):
return "11" if a==1 else "22"
test(a)
>>>'11'
列表推导式生成字典
testlist = [(1,"a"),(2,"b"),(3,"c")]
{x[0]:x[1] for x in testlist}
>>>{1: 'a', 2: 'b', 3: 'c'}
{x:y for x in range(4) for y in range(10,14)}
>>>{0: 13, 1: 13, 2: 13, 3: 13}
使用heapq取最大值和最小值
import heapq
nums = [10,2,9,100,80]
heapq.nlargest(3,nums)
>>>[100, 80, 10]
heapq.nsmallest(3,nums)
>>>[2, 9, 10]
students = [
{"name":"cc","score":100,"height":189},
{"name":"bb","score":10,"height":169},
{"name":"aa","score":80,"height":179}
]
heapq.nsmallest(2,students,key = lambda x:x["height"])
>>>[{'name': 'bb', 'score': 10, 'height': 169},
{'name': 'aa', 'score': 80, 'height': 179}]
用lambda配合filter过滤
testlist = ['color', 'director_name', 'num_critic_for_reviews', 'duration',
'director_facebook_likes', 'actor_3_facebook_likes', 'actor_2_name',
'actor_1_facebook_likes', 'gross', 'genres', 'actor_1_name',
'movie_title', 'num_voted_users', 'cast_total_facebook_likes',
'actor_3_name', 'facenumber_in_poster', 'plot_keywords',
'movie_imdb_link', 'num_user_for_reviews', 'language', 'country',
'content_rating', 'budget', 'title_year', 'actor_2_facebook_likes',
'imdb_score', 'aspect_ratio', 'movie_facebook_likes']
list(filter(lambda x:x.startswith('g'),testlist))
>>>['gross', 'genres']
用lambda配合正则过滤
import re
list(filter(lambda x:re.findall('^(g)',x),testlist))
>>>['gross', 'genres']
testlist = [
{"name":"cc","score":100,"height":189},
{"name":"bb","score":10,"height":169},
{"name":"aa","score":80,"height":179}
]
list(filter(lambda x:"aa" in x.values(),testlist))
>>>[{'name': 'aa', 'score': 80, 'height': 179}]
列表降维
testlist = [1,[2,[3,4]]]
res = []
def fun(s):
for i in s:
if isinstance(i,list):
fun(i)
else :
res.append(i)
fun(testlist)
res
>>>[1, 2, 3, 4]
funa = lambda L: sum(map(funa,L),[]) if isinstance(L,list) else [L]
funa(testlist)
>>>[1, 2, 3, 4]
funb = lambda x:[y for l in x for y in funb(l)] if type(x) is list else [x]
funb(testlist)
>>>[1, 2, 3, 4]
带条件的列表推导式
[x/2 for x in range(10) if x%2==0]
>>>[0.0, 1.0, 2.0, 3.0, 4.0]
[x for x in range(50) if x%5==0 and x%6==0]
>>>[0, 30]
[x+1 if x>=5 else x*10 for x in range(10)]
>>>[0, 10, 20, 30, 40, 6, 7, 8, 9, 10]
testlist = [[1,2,3],[4,5,6],[7,8]]
[y for x in testlist for y in x]
>>>[1, 2, 3, 4, 5, 6, 7, 8]
字典合并
dicta= {"name":"aa","score":80,"height":179}
dictb= {"language":"zh-CN"}
dict(dicta,**dictb)
>>>{'name': 'aa', 'score': 80, 'height': 179, 'language': 'zh-CN'}
dicta.update(dictb)
dicta
>>>{'name': 'aa', 'score': 80, 'height': 179, 'language': 'zh-CN'}