仰之弥高,钻之弥坚,瞻之在前,忽焉在后。 ——致代码
这篇文章收录个人在学习过程中遇到的美妙的代码优化。
- 用正则表达式模仿UNIX系统下的grep功能
#Before:
sum_find = 0
to_find = input("Enter a regular expression: ")
for line in fhand:
if re.search(to_find.encode(),line):
sum_find+=1
#After:
sum_find = sum(bool(re.search(to_find.encode(),line)) for line in fhand)