Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

High-level function supplement

zip

  • Combine two iterable contents into one iterable tuple element type
# zip case
l1 = [1.2.3.4.5]
l2 = [11.22.33.44.55]

z = zip(l1, l2)

print(type(z))

for i in z:
    print(i)
Copy the code
<class 'zip'>
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)
Copy the code
l1 = ["wangwang"."mingyue"."yyt"]
l2 = [89.23.78]

z = zip(l1, l2)

for i in z:
    print(i)
   
l3 = (i for i in z)
print(l3)
Copy the code
('wangwang', 89)
('mingyue', 23)
('yyt', 78)
<generator object <genexpr> at 0x000001ED9F1F3ED0>
Copy the code

enumerate

  • Similar to zip function
  • Each element in the iterable is assigned an index, and the index and content form a tuple
l1 = [11.22.33.44.55]

em = enumerate(l1)

l2 = [i for i in em]
print(l2)
Copy the code
[(0, 11), (1, 22), (2, 33), (3, 44), (4, 55)]
Copy the code
em = enumerate(l1, start=100)

l2 = [i for i in em]
print(l2)
Copy the code
[(100), 11), (101, 22), (102, 33), (103, 44), (104, 55)]Copy the code

The collections module

  • namedtuple
  • deque

namedtuple

  • The tuple type
  • Is a namable tuple
import collections
Point = collections.namedtuple("Point"['x'.'y'])
p = Point(11.22)
print(p.x)
print(p[0])
Copy the code
11
11
Copy the code
Circle = collections.namedtuple("Circle"['x'.'y'.'r'])

c = Circle(100.120.20)
print(c)
print(type(c))

Check which subclass namedTuple belongs to
isinstance(c, tuple)
Copy the code
Circle(x=100, y=120, r=20)
<class '__main__.Circle'>





True
Copy the code
import collections
help(collections.namedtuple)
Copy the code
Help on function namedtuple in module collections:

namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
    Returns a new subclass of tuple with named fields.
    
    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessible by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)
Copy the code

deque

  • It is convenient to solve the efficiency problem caused by frequent deletion and insertion
from collections import deque

q = deque(['a'.'b'.'c'])
print(q)

q.append('d')
print(q)

q.appendleft('x')
print(q)

Copy the code
deque(['a', 'b', 'c'])
deque(['a', 'b', 'c', 'd'])
deque(['x', 'a', 'b', 'c', 'd'])
Copy the code

defaultdict

  • When reading a nonexistent dict property directly, the default value is returned
d1 = {"one":1."two":2."three":3}
print(d1['one'])
print(d1['four'])
Copy the code
1 --------------------------------------------------------------------------- KeyError Traceback (most recent call last)  <ipython-input-34-83fcfcbfcf65> in <module> 1 d1 = {"one":1, "two":2, "three":3} 2 print(d1['one']) ----> 3 print(d1['four']) KeyError: 'four'Copy the code
from collections import defaultdict
The # lambda expression returns a string directly
func = lambda: "ruochen"
d2 = defaultdict(func)

d2["one"] = 1
d2["two"] = 2

print(d2['one'])
print(d2['four'])
Copy the code
1
ruochen
Copy the code

Counter

  • Number of statistics strings
from collections import Counter

# Why does the following result not put abcd... As the key, but as each of the letters as the key
# iterable in parentheses
c = Counter("abcdeabcabc")
print(c)
Copy the code
Counter({'a': 3, 'b': 3, 'c': 3, 'd': 1, 'e': 1})
Copy the code
# help(Counter)
Copy the code
s = {"I"."love"."you"}
c = Counter(s)

print(c)
Copy the code
Counter({'love': 1, 'you': 1, 'I': 1})
Copy the code

Finally, welcome to pay attention to my personal wechat public account “Little Ape Ruochen”, get more IT technology, dry goods knowledge, hot news