10 Python One Liners to Impress Your Friends
2013-01-13 21:35
260 查看
1.列表中的每项乘2
print [2*i for i in range(1,11)]
Or
print map(lambda x: 2*x, range(1,11)) print [-~i*2 for i in range(10)]
2.列表中的数字求和
print sum(range(1,1001))Or
reduce(int.__add__, range(1,1001), 0)
3.检查字符串是否包括单词
wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." print [x in tweet.split() for x in wordlist]Or
print map(lambda x: x in tweet.split(), wordlist)
4. 读取文件
print open("ten_one_liners.py").readlines()
5. Happy Birthday to You!
print ["Happy Birthday to " + ("you" if x != 2 else "dear Name") for x in range(4)]
6. 根据条件把列表分组
print reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
(译者注: 也可以用itertools里的groupby)
7.读取并解析XML Web service
from xml.dom.minidom import parse, parseString import urllib2 # note - i convert it back into xml to pretty print it print parse( urllib2.urlopen("https://cnos.info/proxy/index.php?q=aHR0cDovL3NlYXJjaC50d2l0dGVyLmNvbS9zZWFyY2guYXRvbT8mYW1wO3E9cHl0aG9u&hl=3ed") ).toprettyxml(encoding="utf-8")
8.列表的最大值或最小值
print min([14, 35, -7, 46, 98]) print max([14, 35, -7, 46, 98])
9. 并行处理
import multiprocessing import math print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))
10. 埃拉托斯特尼筛法
n = 50 # We want to find prime numbers between 2 and 50 print sorted(set(range(2,n+1)).difference(set((p * f) for p in range(2,int(n**0.5) + 2) for f in range(2,(n/p)+1))))
相关文章推荐
- One Liners to Impress Your Friends
- [转]Groovy One Liners to Impress Your Friends
- 10 minutes to run every Windows app on your Ubuntu desktop,10分钟在你的UBUNTU中运行WINDOWS应用程序
- 10 Tips for Leading Your Team to Peak Performance(ZT)
- Getting your driver to handle more than one I/O request
- Python3 初学实践案例(10)对象转字典 object to dict
- We are unable to complete the review of your app since one or more of your In App Purchases have not
- Machine Learning Algorithms: Which One to Choose for Your Problem
- 10 ways to make your code more testable
- To pack your python scripts to EXE by using PyInstaller3.0
- How to Accelerate Your Test Automation Execution speed 3-4 times with only one setting
- One python demo to draw 3 bars in one figure
- A Modern Way to Seek Your Friends Overseas
- How to package your python codes?
- 10 Specific Ways to Improve Your Productivity With Emacs
- 44.Your database is functional with a peak load for the last one hour. You want to preserve the perf
- How to create an installer for your Python program
- Link - Windows Azure - Transfer your account to another one
- 10 ways to Improve Your Programming Productivity
- Top 10 Ways to Perfect Your Daily Routine with the Power of Science