轉: 震驚小夥伴的單行代碼 Python篇

轉:http://www.vaikan.com/10-python-one-liners-to-impress-your-friends/html

 

    幾年前,函數式編程的復興正值巔峯,一篇介紹 Scala 中 10 個單行函數式代碼的博文在網上走紅。很快地,一系列使用其餘語言實現這些單行代碼的文章也隨之出現,好比 Haskell, Ruby, Groovy, Clojure, Python, C#, F#, CoffeeScriptpython

每篇文章都使人印象深入的揭示了這些語言中一些出色優秀的編程特徵。編程高手們利用這些技巧提升編程速度、改進軟件質量,編程初學者能從這些簡潔的預防中學到各類編程語言的真諦。本《震驚小夥伴的單行代碼系列》將逐一介紹這些各類編程語言單行代碼文章,供你們學習參考。git

一、讓列表中的每一個元素都乘以2

print map(lambda x: x * 2, range(1,11))

二、求列表中的全部元素之和

print sum(range(1,1001))

三、判斷一個字符串中是否存在某些詞

wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is an example tweet talking about scala and sbt."

print map(lambda x: x in tweet.split(),wordlist)

四、讀取文件

print open("ten_one_liners.py").readlines()

五、祝你生日快樂!

print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),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],([],[]))

7. 獲取XML web service數據並分析

from xml.dom.minidom import parse, parseString
import urllib2
# 注意,我將它轉換成XML格式化並打印出來
print parse(urllib2.urlopen("http://search.twitter.com/search.atom?&q=python")).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. 「Sieve of Eratosthenes」算法

Python裏沒有Sieve of Eratosthenes操做符,但這對於Python來講並非難事。github

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))))
相關文章
相關標籤/搜索