Home  >  Article  >  Backend Development  >  PythonTipsandTraps(一)

PythonTipsandTraps(一)

黄舟
黄舟Original
2016-12-20 17:17:331284browse

1. If you want to get the index and content of a list, you can quickly achieve it through 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. Set in Python is a An unordered set of non-repeating elements can be very convenient for relationship testing and elimination of duplicate 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 Generate a tuple subclass that can use names to access element content, very convenient

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

4, deque The biggest advantage of the double-segment queue is that you can add and delete objects from the head 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 is also in collections and is mainly used To count

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

elements method returns an iterator , will generate all elements known by Counter; most_common(n) generates a sequence, including the most commonly used input values ​​​​and corresponding counts

The above is the content of PythonTipsandTraps(1), for more related content, please pay attention to the PHP Chinese website (www.php .cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn