python application list formula: generating a series of random number sequence

List formula used [] creates a list in which the vessel operates and the operation type of data, to generate a new list, the list formula elegantly simple, there are many application scenarios.
For example: We often need to use a string of random numbers, this time on the need to generate style appearance, we use the following code demonstrates:

from random import random #random库导入要符合规范
gl = [ round(random(),2) for _ in range(10) ]
print(gl)

After running output:

[0.4, 0.97, 0.57, 0.25, 0.17, 0.87, 0.8, 0.84, 0.85, 0.42]
[Finished in 0.4s]

If we need to change the length of the random number list, you only need to change the parameters of range function on it, very convenient. Even it can be packaged as a function, for example:

from random import random
def get_randam_sequence(seq_len):
	return([ round(random(),2) for _ in range(seq_len) ])
print(get_randam_sequence(15))

The results are as follows:

[0.32, 0.88, 0.54, 0.77, 0.32, 0.74, 0.8, 0.57, 0.61, 0.83, 0.18, 0.41, 1.0, 0.55, 0.62]
[Finished in 0.5s]
Published 170 original articles · won praise 9 · views 4547

Guess you like

Origin blog.csdn.net/weixin_41855010/article/details/104481248