1, the time

Get local time

import time
time.localtime()
ime.gmtime()
time.ctime()

Get the timestamp and timer
time.time()
time.perf_counter()
time.process_time()


lctime = time.localtime()
time.strftime("%Y-%m-%d %A %H:%M:%S", lctime)# format output


Copy the code

2, the random

from random import *
from random import *
seed(10)
print(random()) # 0.5714025946899135
seed(10)
print(random()) # 0.5714025946899135
seed(100)
print(random()) # 0.1456692551041303
# Same seed number, same random number generated
# If the number of seeds is not set, the current number of seeds is used
Copy the code
# integer
randint(a,b). Random integer between #[a,b]
randrange(a,b,step) #[a,b) is a random integer with step size between them
randrange(a,) Random integer between #[0, a)

# floating point numberThe random ()Random floating point numbers between # [0.0,1.0)
uniform(a,b) Random floating point number between #[a,b]

# sequence function
choice(seq) Return a random element, either a list or a string
choices(seq,weight-None,k) # k is the number of samplesChoices (["win"."lose"."draw"], [4.5.1].10) # Three arguments: sequence/weight/sampling timesThe shuffle (seq)# Take a random shot of the elements in the sequence and return the scrambled sequenceSample (pop, k)# Select k elements randomly from the pop type and return a list

# Probability distributionGauss (mean, STD)# Generate a random number that conforms to the Gaussian distribution

import matplotlib.pyplot as plt
from random import *
res = [gauss(0.1) for i in range(10000)]
plt.hist(res,bins=1000)
plt.show()


# Random red envelopes
import random
def red_packet(total,num) :
	for i in range(1,num):
		per = random.uniform(0.01,total/(num-i+1) *2)
		total -= per
		print("Red envelope amount: {:.2f} yuan".format(i,per))
	else:
		print("Red envelope amount: {:.2f} yuan".format(num, total)


# Generate captcha randomly
import random,string

 print(string.digits)
 print(string.ascii_letters)

 s = string.digits + string.ascii_letters

 v = random.sample(s,4)
 print(v)
 print("".join(v))

Copy the code

3, the collections

import collections
# collections.namedtuple(typename=,field_names=,rename=False,defaults=None,module=None)
Point = collections.namedtuple("point"["x"."y"])
p = Point(1.7)
print(p)  #point(x=1, y=7)

print(p.x) # 1
print(p.y) # 7

print(p[0])  # 1
print(p[1])   # 7

a,b = p
print(a,b) 7 # 1
Copy the code

Counter function

Return a dictionary

from collections import Counter
s = "Grandma Cow asks Grandma Liu for milk."
colors = ["red"."blue"."red"."green"."blue"."blue"]
con_str = Counter(s)
con_color = Counter(colors)
print(con_str) # Counter ({' milk '5,' cow ', 2, 'looking for' : 1, 'liu: 1, the' buy ': 1})
print(con_color) #Counter({'blue': 3, 'red': 2, 'green': 1})
print(con_color.most_common(2)) #[('blue', 3), ('red', 2)]
Copy the code

Two-way queue deque

from  collections import deque

d = deque("cde")
# print(d) #deque(['c', 'd', 'e'])

# add elements
d.append("f")
d.append("g")
d.appendleft("b")
d.appendleft("a")
print(d) #deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# delete element
d.pop()
d.popleft()
Copy the code

4、 itertools

Permutation and composition iterators

The cartesian product

import itertools

for i in itertools.product("abc"."ABC") :print(i)
"""
('a', 'A')('a', 'B')('a', 'C')
('b', 'A')('b', 'B')('b', 'C')
('c', 'A')('c', 'B')('c', 'C')
"""

for i in itertools.product("abc",repeat=3) :print(i)
"""
('a', 'a', 'a')('a', 'a', 'b')('a', 'a', 'c')('a', 'b', 'a')
('a', 'b', 'b')('a', 'b', 'c')('a', 'c', 'a')('a', 'c', 'b')
('a', 'c', 'c')('b', 'a', 'a')('b', 'a', 'b')('b', 'a', 'c')
('b', 'b', 'a')('b', 'b', 'b')('b', 'b', 'c')('b', 'c', 'a')
('b', 'c', 'b')('b', 'c', 'c')('c', 'a', 'a')('c', 'a', 'b')
('c', 'a', 'c')('c', 'b', 'a')('c', 'b', 'b')('c', 'b', 'c')
('c', 'c', 'b')('c', 'c', 'c')
"""
Copy the code

arrangement

import itertools
for i in itertools.permutations("abcd".3) :print(i)
"""
('a', 'b', 'c')('a', 'b', 'd')('a', 'c', 'b')('a', 'c', 'd')
('a', 'd', 'b')('a', 'd', 'c')('b', 'a', 'c')('b', 'a', 'd')
('b', 'c', 'a')('b', 'c', 'd')('b', 'd', 'a')('b', 'd', 'c')
('c', 'a', 'b')('c', 'a', 'd')('c', 'b', 'a')('c', 'b', 'd')
('c', 'd', 'a')('c', 'd', 'b')('d', 'a', 'b')('d', 'a', 'c')
('d', 'b', 'a')('d', 'b', 'c')('d', 'c', 'a')('d', 'c', 'b')
"""
Copy the code
import itertools
for i in itertools.permutations(range(3)) :print(i)
"" "(0, 1, 2) (0, 2, 1) (1, 0, 2) (1, 2, 0) (2, 0, 1) (2, 1, 0) ", ""
Copy the code

combination

Unrepeatable combination

import itertools
for i in itertools.combinations("abc".2) :print(i)
"""
('a', 'b')
('a', 'c')
('b', 'c')
"""

for i in itertools.combinations(range(4),3) :print(i)
(0, 1, 2) (0, 1, 3) (0, 2, 3) (1, 2, 3) ""
Copy the code

Repeatable combination

import itertools
for i in itertools.combinations_with_replacement("abc".2) :print(i)
"""
('a', 'a')('a', 'b')
('a', 'c')('b', 'b')
('b', 'c')('c', 'c')
"""

for i in itertools.combinations_with_replacement(range(4),3) :print(i)
"" "(0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 0, 3) (0, 1, 1) (0, 1, 2), (0, 1, 3) (0, 2, 2) (0, 2, 3) (0, 3, 3) (1, 1, 1) (1, 1, 2) (1, 1, 3) (1, 2, 2) (1, 2, 3) (1, 3, 3) (2, 2, 2) (2, 2, 3) (2, 3, 3) (3, 3, 3) "" "

Copy the code

Zip zip

Short zipper (without importing python package)

for i in zip("abc"."ABC"."1234") :print(i)

"""
('a', 'A', '1')
('b', 'B', '2')
('c', 'C', '3')
"""
Copy the code

Long zipper (need to import iterTools package)

import itertools

for i in itertools.zip_longest("abc"."ABCD"."12345") :print(i)

"""
('a', 'A', '1')('b', 'B', '2')('c', 'C', '3')(None, 'D', '4')(None, None, '5')
"""

# when there is a substitute value
import itertools

for i in itertools.zip_longest("abc"."ABCD"."12345",fillvalue="#") :print(i)
"""
('a', 'A', '1')('b', 'B', '2')('c', 'C', '3')('#', 'D', '4')('#', '#', '5')
"""

Copy the code

Infinite iterator

itertools.count(start=0,step=1) itertools. Cycle (" ABC ")for i in itertools.repeat(10.3) :print(i)
Copy the code

other

chain

import itertools

for i in itertools.chain("abc"."efg"[1.2.3) :print(i) # a b c e f g 1 2 3  
Copy the code

enumerate(iterable,start)

for i in enumerate("python") :print(i) # 
"""
(0, 'p')(1, 'y')
(2, 't')(3, 'h')
(4, 'o')(5, 'n')
"""
Copy the code

groupby(iterable,key = None)

import itertools

for k,v in itertools.groupby("aaaabbbbbdbbdbbbdddccccccfffff") :print(k,list(v)) # v returns an iterator
"""
a ['a', 'a', 'a', 'a']
b ['b', 'b', 'b', 'b', 'b']
d ['d']
b ['b', 'b']
d ['d']
b ['b', 'b', 'b']
d ['d', 'd', 'd']
c ['c', 'c', 'c', 'c', 'c', 'c']
f ['f', 'f', 'f', 'f', 'f']
"""



import itertools

animals = ["duck"."tiger"."rat"."bear"."bat"."lion"]
animals.sort(key=lambda x:x[0]) #['bear', 'bat', 'duck', 'lion', 'rat', 'tiger']
print(animals)
for key,group in itertools.groupby(animals,key = lambda x:x[0) :print(key,list(group))
"""
b ['bear', 'bat']
d ['duck']
l ['lion']
r ['rat']
t ['tiger']
"""



Copy the code