Python has a lot of built-in functions, and flexible usage can help a lot.
slice
Slicing is a good helper when we need to intercept list
or get its inverse order.
>>> l = [0, 1, 2, 3]
>>> l[:]
[0, 1, 2, 3]
>>> l[2:]
[2, 3]
>>> l[:3]
[0, 1, 2]
>>> l[1:3]
[1, 2]
>>> l[::-1]
[3, 2, 1, 0]
>>> l[-1:-2:-1]
[3]
The syntax is that r = l[i:j:s]
here we explain the meaning of these parameters:
letter | meaning | describe |
---|---|---|
s | step size | By default1 |
i | start element position | when s> 0 , default is 0 , when s< 0 , default is-1 |
j | Terminating element position (excluding the element, i.e. [ i , j )) |
when s> 0 , default is len(r) , when s< 0 , default is-len(r)-1 |
The corresponding built-in functionslice()
>>> myslice=slice(0,2)
>>> myslice
slice(0, 2, None) # 分别对应 [i, j, s]
>>> l[myslice]
[0, 1]
set operations
>>> before = [0, 1, 2]
>>> after = [1, 2, 3]
>>> print(list(set(before) & (set(after))))
[1, 2]
>>> list_union = list(set(before) | (set(after)))
>>> list_union
[0, 1, 2, 3]
>>> add_items = list(set(list_union) - (set(before)))
>>> add_items
[3]
>>> del_items = list(set(list_union) - (set(after)))
>>> del_items
[0]
From this we draw the detailed differences between the two lists before and after.
set()
Functions can create an unordered set of non-repeating elements, perform relationship testing, remove duplicate data, and compute intersection (&), difference (-), union (|), and more.
Floating-point precision control
Generally we use the round()
function control the precision of floating point numbers.
>>> round(1.1)
1
>>> round(1.12, 1)
1.1
>>> round(1.123, 2)
1.12
The first parameter is a floating point number, the second parameter is the number of decimal places reserved, optional, if not written, it will be reserved to integer by default.
If the precision after interception is required, follow the link below:
Python's little pit about the round function
Why doesn't Python solve the rounding "bug"?