日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

使用python怎樣產(chǎn)生10個(gè)不同的隨機(jī)數(shù)_python

作者:卷耳Journey ? 更新時(shí)間: 2022-09-09 編程語(yǔ)言

怎樣產(chǎn)生10個(gè)不同的隨機(jī)數(shù)

python產(chǎn)生10個(gè)不同隨機(jī)數(shù)的方法:首先創(chuàng)建一個(gè)result的結(jié)果空列表;然后循環(huán)直到result的長(zhǎng)度超過(guò)10退出循環(huán),循環(huán)里面隨機(jī)生成一個(gè)1-10之間的數(shù);最后查看生成的num隨機(jī)數(shù)是否在result列表里,不在就添加進(jìn)去。

1、第一種

range(1,10)生成一個(gè)1-10之間的列表,接著利用random的sample方法。從序列里面選出10個(gè)不同的數(shù)字。

2、第二種

創(chuàng)建一個(gè)result的結(jié)果空列表,然后循環(huán)直到result的長(zhǎng)度超過(guò)10退出循環(huán),循環(huán)里面隨機(jī)生成一個(gè)1-10之間的數(shù),先查看生成的num隨機(jī)數(shù)是否在result列表里,不在就添加進(jìn)去。

3、第三種

先利用range()方法生成一個(gè)1-10的序列,然后利用shuffle方法將temp有序列表達(dá)打亂成無(wú)序的列表,接著利用列表生成式直接循環(huán)遍歷到一個(gè)新列表就可以了。

隨機(jī)產(chǎn)生10個(gè)0~100之間的隨機(jī)數(shù)并求和

實(shí)現(xiàn)代碼

import random
list=[] ?#存儲(chǔ)數(shù)據(jù)范圍的列表
for i in range(0,100):
?? ?list.append(i) #初始化,數(shù)據(jù)范圍:0-100
for j in range(0,10):# 遍歷10次
?? ?print(random.choice(list))# 每次隨機(jī)選擇

輸出結(jié)果:

87
40
48
87
3
8
12
79
62
29

代碼優(yōu)化

產(chǎn)生n個(gè)w范圍之間的隨機(jī)數(shù),并求和

import random

random_number = []  # 存儲(chǔ)產(chǎn)生的隨機(jī)數(shù)
def random_generate(n,w):  #n為產(chǎn)生的隨機(jī)數(shù)的數(shù)量,w為隨機(jī)數(shù)的范圍
    list=[]  #存儲(chǔ)數(shù)據(jù)范圍的列表

    for i in range(0,w):
        list.append(i) #初始化,數(shù)據(jù)范圍:0-w
    for j in range(1,n+1):# 遍歷n次
        tem=random.choice(list) #臨時(shí)變量,否則每次產(chǎn)生的隨機(jī)數(shù)不一樣
        random_number.append(tem)


        #print("第",j,"個(gè)產(chǎn)生的隨機(jī)數(shù)為",tem)# 每次隨機(jī)選擇
        print("{0:^3}-->{1:^5}".format(j,tem))

def sum():
    total=0
    for z in random_number:
        total=z+total
    print("隨機(jī)數(shù)求和:",total)
    #print(total)


if __name__ == "__main__":
    print("隨機(jī)數(shù):")
    random_generate(10,100)
    sum()

輸出:

隨機(jī)數(shù):
?1 --> 66 ?
?2 --> 17 ?
?3 --> 45 ?
?4 --> 58 ?
?5 --> 23 ?
?6 --> 86 ?
?7 --> 37 ?
?8 --> 84 ?
?9 --> 37 ?
10 --> 27 ?
隨機(jī)數(shù)求和: 480

原文鏈接:https://blog.csdn.net/weixin_28787115/article/details/113503627

欄目分類
最近更新