Python random number generation

1.random.random()

import random
print random.random() #0.834407670706

This is a simple creation method, but we usually need to parameterize a set of random numbers and specify a range to create random numbers.

2.random.uniform()

import random
print random.uniform(1,10)#2.27698969238

This method is to generate a random number in a specified range, float type.

import random
print random.randint(1,10)#3

The difference between this and the above is that a random integer is generated.

3.random.range()

import random
print random.randrange(10,1,-3)#10

This method can generate random numbers according to the specified step size.

4.random.choice()

item=[1,2,3,4,5]
print random.choice('nihaowangwentao')#e
print random.choice(item)#5

This method is to select one from the given list as a random number, but it also has a disadvantage that it can only be generated individually.

5.random.shuffle()

import random
item=[1,2,3,4,5]
random.shuffle(item)
print item#[4, 1, 3, 5, 2]

Given a list, shuffle the list.

6.random.sample()

import random
item=[1,2,3,4,5]
print random.sample(item,2)#[4, 5]

This method is to randomly select a specified number of random numbers in a given list.

7. Application - parameter one-dimensional random number

# _*_ coding:utf-8 _*_
import random
def dataint(down,up,k):
    """
    产生多维随机整数
    :param down:
    :param up:
    :param k:
    :return:
    """
    data=[]
    for i in range(k):
        temp = random.randint(down, up)
        data.append(temp)
    return data
print dataint(1,10,10)#[7, 1, 2, 8, 2, 4, 2, 8, 4, 9]

This is to generate a set of multidimensional random numbers,

# _*_ coding:utf-8 _*_
import random
def dataint(down,up,k):
    """
    产生多维随机整数
    :param down:
    :param up:
    :param k:
    :return:
    """
    data=[]
    for i in range(k):
        temp = random.uniform(down, up)
        data.append(temp)
    return data
print dataint(1,10,10)#[7.963157134285984, 7.668861729299904, 2.0627102553927257, 6.3624214066153035, 4.197435315071023, 4.169695244423517, 3.6555993007085474, 3.0851608684981655, 6.1487965864173075, 7.113803486261753]

This is an array of type float.

8. Generate a random array in the form of a matrix

# _*_ coding:utf-8 _*_
import random
import numpy as np
def dataint(down,up,k):
    """
    产生多维随机整数
    :param down:
    :param up:
    :param k:
    :return:
    """
    data=[]
    for i in range(k):
        temp = random.uniform(down, up)
        temp1 = random.uniform(down, up)
        data.append([temp,temp1])
    return data
data=dataint(1,10,10)
data=np.array(data)
data=data.tolist()
print data

Here we use it twice to generate random arrays.

This article is reproduced from the Internet. If there is any infringement, please contact to delete it. The copyright belongs to the original author.
Reposted from blog: https://www.jianshu.com/p/374335e3be57

Guess you like

Origin blog.csdn.net/TommyXu8023/article/details/105281949