0. Dictionary initialization
D = {' A ': 1, ' B ': 2}
or d={}
D[' a '] = 1
D[' B '] = 2
is not like JSON format data, syntax and JavaScript are very similar
1. Variable Accept sequence decomposition:
p = (3.14,8.23)
X, y = P
Print (x, y)
3.14,8.23
2. Collections.deque fixed length queue.
>>> from collections Import deque
>>> p = deque (MaxLen = 2)
>>> p.append (3.14)
>>> P.append (8.23)
>>> P
Deque ([3.14, 8.23], maxlen=2)
3. HEAPQ maximum minimum value.
>>> Import HEAPQ
>>> p = [3.14,8.23,7.10]
>>> Heapq.nlargest (1,p)
[8.23]
>>> Heapq.nsmallest (1,p)
[3.14]
5. Find two dictionaries of the same key and same item
>>> from collections Import Ordereddict
>>> d = {}
>>> d[' a '] = 1
>>> d[' c '] = 3
>>> d[' b '] = 2
>>> dd = {}
>>> dd[' a '] = 3
>>> dd[' e '] = 5
>>> dd[' b '] = 2
>>> D.keys () & Dd.keys ()
{' A ', ' B '}
>>> d.items () & Dd.items ()
{(' B ', 2)}
6 Remove array or dictionary value duplicate element set
>>> D ={1,1,2,2,3,3,4,5}
>>> Set (d)
{1, 2, 3, 4, 5}
7 Intercepting array elements
>>> d = [1,1,2,2,3,3,4,5]
>>> D[2:4]
[2, 2]
>>> D[2:5]
[2, 2, 3]
8 statistics element Occurrences Counter.most_common.
>>> d = [1,1,1,2,2,4,5]
>>> from collections Import Counter
>>> master = Counter (d). Most_common (2)
>>> Print (Master)
[(1, 3), (2, 2)]
4. Collections. Ordereddict ordered Dictionary
>>> from collections Import Ordereddict
>>> d = ordereddict ()
>>> d[' a '] = 1
>>> d[' c '] = 3
>>> d[' b '] = 2
>>> Print (d)
Ordereddict (' A ', 1), (' C ', 3), (' B ', 2)])
9. Array sorting Operator.itemgetter
>>> from operator Import Itemgetter
>>> d = [2,1,5,4,3]
>>> Sorted (d)
[1, 2, 3, 4, 5]
10. Sort Dictionary
>>> from operator Import Itemgetter
>>> p = [{' X ': ' 3 ', ' Y ': ' 3 '},{' x ': ' 4 ', ' Y ': ' 4 '},{' x ': ' 2 ', ' Y ': ' 2 '},{' x ': ' 1 ', ' y ': ' 1 '}]
>>> P.sort (Key=itemgetter (' x '))
>>> Print (P)
[{' X ': ' 1 ', ' y ': ' 1 '}, {' X ': ' 2 ', ' Y ': ' 2 '}, {' X ': ' 3 ', ' Y ': ' 3 '}, {' X ': ' 4 ', ' Y ': ' 4 '}]
One-to-one lambda expressions
>>> p = [{' X ': ' 3 ', ' Y ': ' 3 '},{' x ': ' 4 ', ' Y ': ' 4 '},{' x ': ' 2 ', ' Y ': ' 2 '},{' x ': ' 1 ', ' y ': ' 1 '}]
>>> plamb = [n[' x '] > ' 2 ' for n in P]
>>> Print (PLAMB)
[True, True, False, false]
The compress is used in conjunction with 11 items.
>>> from Itertools Import compress
>>> list (compress (P,PLAMB))
[{' X ': ' 3 ', ' Y ': ' 3 '}, {' X ': ' 4 ', ' Y ': ' 4 '}]
13. Logically merging objects
>>> p = {' x ': 1, ' Y ': 2}
>>> P2 = {' Y ': 3, ' Z ': 4}
>>> from collections Import Chainmap
>>> C = Chainmap (P,P2)
>>> Print (c)
Chainmap ({' X ': 1, ' Y ': 2}, {' Y ': 3, ' Z ': 4})
>>> list (C.keys ())
[' x ', ' z ', ' y ']
Python Common data structures