Python Tips and Traps (1), pythontraps
Most of the content is from www.airpair.com/python/posts/python-tips-and-traps, author @ Ryan Brown
1. If you want to get the index and content of a list, you can use enumerate to quickly implement
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. set in Python is an unordered, non-repeating element set. It is very convenient to test the relationship and eliminate repeated elements.
# 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 generates a tuple subclass that can access element content by name, which is very convenient.
import collectionshttp:LightObject = collections.namedtuple('LightObject', ['shortname', 'otherprop'])n = LightObject(shortname = 'something', otherprop = 'something else')n.shortname # something
4. deque dual-segment queue. The biggest benefit is that objects popleft () and appendleft () can be added and deleted from the header ()
import collectionsd = collections.deque('123456')print d.popleft() # '1'd.appendleft('7')print d # deque(['7','2','3','4','5','6'])
5. Counter is also in collections and is mainly used to count
import collectionsc = collections.Counter('abcab')print c #Couner({'a':2,'b':2,'c':1}
The elements method returns an iterator that generates all elements known to Counter. most_common (n) generates a sequence that contains the most common input values and corresponding counts.