python takes a list of random non-repeating numbers and applies

python takes a list of random non-repeating numbers and applies

the code

Without further ado, go directly to the code

#产生 1 - n 之间不重复随机数
def GetRandomNumList(len):
    rsList = []
    for i in range(0,len):
        rsList.append(i)
    for i in range(0,len):
        num = random.randint(0,len)
        tmp = rsList[i]
        rsList[i] = rsList[num]
        rsList[num] = tmp    
    return rsList

practical application

For example, we need to randomly pick out a few products from the dessert list, so we can do this

import random

DessertList=[
	'煎饼果子',
	'汉堡',
	'寿司',
	'炭烧酸奶一杯',
	'蛋挞2个',
	'山竹',
	'芒果',
	'寿司',
	'丹麦奶酪',
	'牛奶1盒',
	'红毛丹'
]

def Dessert():
    txt="宵夜推荐:"
    t_t=GetRandomNumList(11)#11种甜品
    t_l=random.randint(1,2)#两种宵夜搭配类型
    if t_l==1 : #类型一:5甜品
        for i in range(0,5):
            if i != 4:
                txt=txt+DessertList[t_t[i]]+"+"
            else:
                txt=txt+DessertList[t_t[i]]
    else:  #类型二:1甜品
        txt=txt+DessertList[t_t[1]]
    return txt
    
#产生 1 - n 之间不重复随机数
def GetRandomNumList(len):
    rsList = []
    for i in range(0,len):
        rsList.append(i)
    for i in range(0,len):
        num = random.randint(0,len)
        tmp = rsList[i]
        rsList[i] = rsList[num]
        rsList[num] = tmp    
    return rsList

print(Dessert())

Then we can get a midnight snack recommendation: 2 egg tarts + Danish cheese + a cup of charcoal-grilled yogurt + sushi + 1 box of milk

Guess you like

Origin blog.csdn.net/weixin_45371411/article/details/122162754