PythonTipsandTraps(一)

來源:互聯網
上載者:User
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: sorry, we no longer 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(menu)print ('At one time or another, we have served ', ','.join(full_menu))

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

import collectionshttp:
LightObject = collections.namedtuple('LightObject', ['shortname', 'otherprop'])
n = LightObject(shortname = 'something', otherprop = 'something else')
n.shortname # something

4、deque 雙段隊列,最大好處就是可以從頭部添加和刪除對象 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(一)的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.