您的位置:首页 > 编程语言 > Python开发

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))))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: