單行代碼 之Python 3.5版

==========================================================================html

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

在網上看到有python2.7的單行代碼(連接如上):python

自學python3.x中,因而簡單的想將2.x版翻譯成3.x版。其中第7條實現還未成功。待了解xml後再嘗試。web

==========================================================================算法

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

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

==========================================================================python3.x

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

print(sum(range(1,101)))

==========================================================================app

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

wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is a example tweet talking about scala and sbt"
print(list(map(lambda x: x in tweet.split(),wordlist)))

==========================================================================dom

五、祝你生日快樂!

print(list(map(lambda x: "happy birthday to " + ("you" if x != 2 else "dear name"), range(4))))

==========================================================================python2.7

6. 過濾列表中的數值

from functools import reduce
reduce(lambda a,c: (a[0]+[c],a[1]) if c > 60 else (a[0],a[1]+[c]), [49, 58, 76, 82, 88, 90],([],[]))

==========================================================================post

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

待定atom

from xml.dom.minidom import parse, parseString
import urllib.request
# 注意,我將它轉換成XML格式化並打印出來
print(parse(urllib.request.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」算法

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,int(n/p)+1)))))
相關文章
相關標籤/搜索