首頁  >  文章  >  後端開發  >  Python技巧與陷阱(一)

Python技巧與陷阱(一)

黄舟
黄舟原創
2016-12-20 17:17:331283瀏覽

1、如果想要得到一個清單的index和內容,可以透過enumerate快速實現

drinks = ['coffee','tea', 'milk', 'water']for index, drink in enumerate(drinks):    PRint ( 'Item {} is {}'.format(index, drink))#Result# Item 0 is coffee# Item 1 is tea# Item 2 is milk# Item 3 is water

2、Python 中的set, 是一個無序不重複元素集,可以非常方便的進行關係測試和消除重複元素

# deduplicate a list fastprint (set(['ham', 'eggs','bacon','ham']))# Result# {'ham', 'eggs', 'bacon'}
# compare list to find difference/similarities # {} without "key":"value" pairs makes a setmenu = {'pancakes', 'ham', 'eggs' , 'bacon'}
new_menu = {'coffee', 'ham', 'eggs', 'bagels', 'bacon'}

new_items = new_menu.difference(menu)print ('try our new', ', ' .join(new_items))# Result: try our new coffee, bagelsdiscontinued_items = menu.difference(new_menu)print ('sorry, we no longer have', ', '.join(discontinued_items))# Result: weak', ', '.join(discontinued_items))# Res have panckes
old_items = new_menu.intersection(menu)print ('Or get the same old', ', '.join(old_items))# Result: Or ger the same old eggs, ham, baconfull_menu = new_menu.union( print ('At one time or another, we have served ', ','.join(full_menu))

3、namedtuple    產生可以使用名字來存取元素內容的tuple 子類,非常方便

: collat​​​​nection LightObject = collections.namedtuple('LightObject', ['shortname', 'otherprop'])
n = LightObject(shortname = 'something', otherprop = 'something else')
n.shortname  # something

雙段佇列,最大好處是可以從頭部新增和刪除物件popleft()、 appendleft()

import collections

d = collections.deque('123456')print d.popleft()  # '1'd.appendleft ('7')print d #  deque(['7','2','3','4','5','6'])



5、Counter 同樣是collections 中的,主要用來計數

import collections

c = collections.Counter('abcab')print c #Couner({'a':2,'b':2,'c':1}



elements 方法回傳一個迭代器,將產生Counter 所知道的所有元素;most_common(n)產生一個序列,包含最常用的輸入值及對應計數

 以上就是PythonTipsandTraps(一)的內容,更多相關內容請關注PHP中文網(www.php .cn)! 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn