給Python初學者的一些技巧

交換變量

Python代碼 
  1. x = 6
  2. y = 5
  3. x, y = y, x
  4. print x
  5. >>> 5
  6. print y
  7. >>> 6
if 語句在行內

Python代碼 
  1. print "Hello" if True else "World"
  2. >>> Hello

連接 下面的最後一種方式在綁定兩個不同類型的對象時顯得很cool。

Python代碼 
  1. nfc = ["Packers""49ers"]
  2. afc = ["Ravens""Patriots"]
  3. print nfc + afc
  4. >>> ['Packers''49ers''Ravens''Patriots']
  5. print str(1) + " world"
  6. >>> 1 world
  7. print `1` + " world"
  8. >>> 1 world
  9. print 1"world"
  10. >>> 1 world
  11. print nfc, 1
  12. >>> ['Packers''49ers'1
數字技巧
Python代碼 
  1. #除後向下取整
  2. print 5.0//2
  3. >>> 2
  4. # 2的5次方
  5. print 2**5
  6. >> 32
注意浮點數的除法
Python代碼 
  1. print .3/.1
  2. >>> 2.9999999999999996
  3. print .3//.1
  4. >>> 2.0
數值比較 這是我見過諸多語言中很少有的如此棒的簡便法
Python代碼 
  1. x = 2
  2. if 3 > x > 1:
  3.   print x
  4. >>> 2
  5. if 1 < x > 0:
  6.   print x
  7. >>> 2
同時迭代兩個列表
Python代碼 
  1. nfc = ["Packers""49ers"]
  2. afc = ["Ravens""Patriots"]
  3. for teama, teamb in zip(nfc, afc):
  4.   print teama + " vs. " + teamb
  5. >>> Packers vs. Ravens
  6. >>> 49ers vs. Patriots
帶索引的列表迭代
Python代碼 
  1. teams = ["Packers""49ers""Ravens""Patriots"]
  2. for index, team in enumerate(teams):
  3.   print index, team
  4. >>> 0 Packers
  5. >>> 1 49ers
  6. >>> 2 Ravens
  7. >>> 3 Patriots
列表推導式已知一個列表,我們可以刷選出偶數列表方法:
Python代碼 
  1. numbers = [1,2,3,4,5,6]
  2. even = []
  3. for number in numbers:
  4.   if number%2 == 0:
  5.     even.append(number)
轉變成如下:
Python代碼 
  1. numbers = [1,2,3,4,5,6]
  2. even = [number for number in numbers if number%2 == 0]
字典推導和列表推導類似,字典可以做同樣的工作:
Python代碼 
  1. teams = ["Packers""49ers""Ravens""Patriots"]
  2. print {key: value for value, key in enumerate(teams)}
  3. >>> {'49ers'1'Ravens'2'Patriots'3'Packers'0}
初始化列表的值
Python代碼 
  1. items = [0]*3
  2. print items
  3. >>> [0,0,0]
列表轉換爲字符串
Python代碼 
  1. teams = ["Packers""49ers""Ravens""Patriots"]
  2. print ", ".join(teams)
  3. >>> 'Packers, 49ers, Ravens, Patriots'
從字典中獲取元素
我承認try/except代碼並不雅緻,不過這裏有一種簡單方法,嘗試在字典中查找key,如果沒有找到對應的alue將用第二個參數設爲其變量值。
Python代碼 
  1. data = {'user'1'name''Max''three'4}
  2. try:
  3.   is_admin = data['admin']
  4. except KeyError:
  5.   is_admin = False
替換成這樣:
Python代碼 
  1. data = {'user'1'name''Max''three'4}
  2. is_admin = data.get('admin'False)
獲取列表的子集有時,你只需要列表中的部分元素,這裏是一些獲取列表子集的方法。
Python代碼 
  1. x = [1,2,3,4,5,6]
  2. #前3個
  3. print x[:3]
  4. >>> [1,2,3]
  5. #中間4個
  6. print x[1:5]
  7. >>> [2,3,4,5]
  8. #最後3個
  9. print x[3:]
  10. >>> [4,5,6]
  11. #奇數項
  12. print x[::2]
  13. >>> [1,3,5]
  14. #偶數項
  15. print x[1::2]
  16. >>> [2,4,6]
60個字符解決FizzBuzz
前段時間Jeff Atwood 推廣了一個簡單的編程練習叫FizzBuzz,問題引用如下:
寫一個程序,打印數字1到100,3的倍數打印“Fizz”來替換這個數,5的倍數打印“Buzz”,對於既是3的倍數又是5的倍數的數字打印“FizzBuzz”。
這裏就是一個簡短的,有意思的方法解決這個問題:
Python代碼 
  1. for x in range(101):print"fizz"[x%3*4::]+"buzz"[x%5*4::]or x
集合
除了python內置的數據類型外,在collection模塊同樣還包括一些特別的用例,在有些場合Counter非常實用。如果你參加過在這一年的Facebook HackerCup,你甚至也能找到他的實用之處。
Python代碼 
  1. from collections import Counter
  2. print Counter("hello")
  3. >>> Counter({'l'2'h'1'e'1'o'1})
迭代工具
和collections庫一樣,還有一個庫叫itertools,對某些問題真能高效地解決。其中一個用例是查找所有組合,他能告訴你在一個組中元素的所有不能的組合方式
Python代碼 
  1. from itertools import combinations
  2. teams = ["Packers""49ers""Ravens""Patriots"]
  3. for game in combinations(teams, 2):
  4.   print game
  5. >>> ('Packers''49ers')
  6. >>> ('Packers''Ravens')
  7. >>> ('Packers''Patriots')
  8. >>> ('49ers''Ravens')
  9. >>> ('49ers''Patriots')
  10. >>> ('Ravens''Patriots')
False == True
比起實用技術來說這是一個很有趣的事,在python中,True和False是全局變量,因此:
Python代碼 
  1. False = True
  2. if False:
  3.   print "Hello"
  4. else:
  5.   print "World"
  6. >>> Hello
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章