Python的一些單行代碼(摘抄)

來源:互聯網
上載者:User

標籤:sse   lin   擷取   import   並行   最小   tip   pen   cal   

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

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

2、求列表中的所有元素之和

print sum(range(1,1001))

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

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)

4、讀取檔案

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

5、祝你生日快樂!

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, parseStringimport 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 multiprocessingimport math

print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))

10. “Sieve of Eratosthenes”演算法

Python裡沒有Sieve of Eratosthenes操作符,但這對於Python來說並不是難事。

n = 50 # We want to find prime numbers between 2 and 50print 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))))

Python的一些單行代碼(摘抄)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.