Python cookbook 3rd__python

Source: Internet
Author: User
Tags dedupe
# coding=utf-8 # Remove First, last, average def avg (rest): return sum (REST)/rest.__len__ () def Drop_first_last (grades): Fir St, *middle, last = grades return avg (middle) print (Drop_first_last (99,2,3,4,5,6,7,8,1)) # asterisk expression is very good when the iteration element is a sequence of variable long tuples  Records = [(' foo ', 1, 2), (' Bar ', ' Hello '), (' Foo ', 3, 4),] def do_foo (x, y): Print (' foo: ', X, y) def Do_bar (s): Print (' bar: ', s) for tag, *args in records:if tag = = ' Foo ': Do_foo (*args) elif tag = = ' Ba R ': Do_bar (*args) # asterisk decompression syntax can also be useful in string manipulation, such as String segmentation uname, *fields, homedir, sh = ' nobody:*:-2:-2:unprivileged User  :/var/empty:/usr/bin/false '. Split (': ') head, *tail = [1, 7, 4, 5, 9] Print (UNAME,HOMEDIR,SH) # to extract some elements and discard them, you can't simply use the * 


, but you can use an ordinary discarded name, such as or IGN record = (' ACME ', 123.45, (a)) name, *_, (*_, year) = record print (name, year) # do a simple text match on multiple lines and return the first N lines of the matching row # Keep a limited history it's Collections.deque's time to do it. Deque can always append, the append that is greater than 5 will squeeze out the first from Colle Ctions Import Deque defSearch (lines, pattern, history=5): Previous_lines = deque (maxlen=history) for Li in lines:if pattern in L I:yield Li, previous_lines previous_lines.append (LI) with open (R ' test_api.py ') as F:for line, p
        Revlines in search (f, ' App_context ', 5): For Pline in Prevlines:print (Pline,) print (line,)
Print ('-' * 20) # Gets the list of the largest or smallest N elements in a collection. # The HEAPQ module has two functions: Nlargest () and nsmallest () can solve the problem perfectly. # Two functions can accept a keyword parameter for more complex data structures: import HEAPQ nums = [1, 8, 2, 23, 7, 4 2] heapq.heapify (nums) #底层实现里面, first the collection data is sorted and placed in a list of print (Heapq.nlargest (3, Nums)) # prints [42, 37, 2
    3] Print (Heapq.nsmallest (3, Nums)) # prints [ -4, 1, 2] portfolio = [{' Name ': ' IBM ', ' shares ': $, ' Price ': 91.1}, {' name ': ' AAPL ', ' shares ': $, ' Price ': 543.22}, {' name ': ' FB ', ' shares ': ' Price ': 21.09}, {' name ': ' HPQ ', ' Shares ': "Price": 31.75}, {' name ': ' YHOO ', ' shares ': ', ' Price ': 16.35}, {' Name ': 'ACME ', ' shares ': $, ' Price ': 115.65}] Print (Heapq.nsmallest (3, Portfolio, Key=lambda s:s[' price ')) print (Heapq.nlarge
        St (3, Portfolio, Key=lambda s:s[' price ')) # priority HEAPQ Queue import HEAPQ class Priorityqueue:def __init__ (self): Self._queue = [] Self._index = 0 def push (self, item, priority): Heapq.heappush (Self._queue,-prio Rity, Self._index, item) Self._index + + 1 def pop (self): return Heapq.heappop (Self._queue) [-1] Clas S item:def __init__ (self, name): Self.name = name def __repr__ (self): return ' Item ({!r}) '. Format ( Self.name) Q = Priorityqueue () Q.push (item (' foo '), 1) Q.push (item (' Bar '), 5) Q.push (item (' Spam '), 4) Q.push (item (' Grok ') , 1) The keys in print (Q.pop ()) print (Q.pop ()) print (Q.pop ()) print (Q.pop ()) # Dictionary map multiple values, # Use collections in Defaultdict modules to construct such words # Choose whether to use a list or a collection depends on your actual needs.
If you want to keep the elements in the order of insertion, use the list and use the collection if you want to remove the repeating element (and don't care about the order of the elements). From collections import Defaultdict d = defaultdict (list) d[' a '].append (1) d[' A '].append (2) d[' A '].append (2) d[' B '].append (4) dd = defaultdict (set) dd[' A '].add (1) dd[' A '].add (2) dd[' a '].
Add (2) dd[' B '].add (4) print (d, DD) # Dictionary operations (such as minimum, maximum, sort, and so on). Prices = {' ACME ': 45.23, ' AAPL ': 612.78, ' IBM ': 205.55, ' HPQ ': 37.20, ' FB ': 10.75} min_price = min (z IP (prices.values (), Prices.keys ())) Max_price = max (Zip (prices.values (), Prices.keys ())) prices_sorted = sorted (Zip (
Prices.values (), Prices.keys ()) min (Prices.values ()) # Returns 10.75 Max (Prices.values ()) # Returns 612.78 # Find the same point in two dictionaries # Construct a new dictionary with an existing dictionary that excludes several specified keys a = {' X ': 1, ' Y ': 2, ' Z ': 3} b = {' W ': Ten, ' X ': one, ' Y ': 2} # Fin  D-Keys in common A.keys () & B.keys () # {' X ', ' Y '} # Find the keys in a that is are not in B a.keys ()-B.keys () # {' Z '} # Find (Key,value) pairs in common A.items () & B.items () # {(' Y ', 2)} # Make a new dictionary with certain keys Remov ed C = {Key:a[key] for key in A.keys ()-{' Z ', ' W '}} # c is {' X ': 1, ' Y ': 2} # Delete the same elements in the sequence and keep the order


def dedupe (items): Seen = set () for item in Items:if item not in Seen:yield item Seen.add (item) # DICT type def dedupefordict (items, key=none): Seen = set () for item in Items:val = ITE  M if key is None else key (item) if Val not in Seen:yield item Seen.add (val) a = [1, 5, 2, 1, 9, 1, 5, ten] b = [{' X ': 1, ' Y ': 2}, {' X ': 1, ' Y ': 3}, {' X ': 1, ' Y ': 2}, {' X ': 2, ' Y ': 4}] Print (set (a)) # The element position in the resulting result is In the following way, you can resolve print (list (Dedupe (a))) Print (List (dedupefordict (b, Key=lambda D: (d[' x ', d[' y '))) Print (List ( Dedupefordict (b, Key=lambda d:d[' x '))] # 1.12 The most frequently occurring element in the sequence, the Counter object is actually a dictionary that maps the element to the number of times it appears from collections import Cou nter words = [' look ', ' in ', ' my ', ' Eyes ', ' look ', ' in ', ' my ', ' Eyes ', ' the ', ' Eyes ', ' the ', ' Eyes ', ' the ', ' E Yes ', ' not ', ' around ', ' the ', ' Eyes ', ' don ' t ', ' look ', ' around ', ' the ', ' Eyes ', ' look ', ' in ', ' my ', ' Eyes ', ' ' Re ', ' under '] morewords = [' Why ', ' aRe ', ', ', ' not ', ' looking ', ' in ', ' my ', ' eyes '] word_counts = Counter (words) word_counts.update (morewords) Top_three = W Ord_counts.most_common (3) # The highest frequency 3 words print (top_three) # outputs [(' Eyes ', 8], (' The ', 5), (' Look ', 4)] Print (Word_cou nts[' not '] # 1 print (word_counts[' Eyes ') # 8 # 1.13 Sort a dictionary list by a keyword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.