Maximum and minimum assignment tips in Python of share
- 2020-06-19 10:49:41
- OfStack
When coding codes, it is sometimes necessary to assign values according to the comparison size:
import random
seq = [random.randint(0, 1000) for _ in range(100)]
# methods 1 :
xmax, xmin = max(seq), min(seq)
# methods 2 :
xmax, *_, xmin = sorted(seq)
The advantages of method 2 are not obvious from the above one, but we usually compare the size of two Numbers and select:
dx, dy = random.sample(seq, 2)
# methods 1 :
dx, dy = min(dx, dy), max(dx, dy)
# methods 2 :
dx, dy = sorted((dx, dy))
You can still type a few fewer letters