這篇文章主要介紹了Python生成不重復隨機值的方法,實例分析了Python算法實現與Python自帶方法的實現技巧,非常簡單實用,需要的朋友可以參考下
本文實例講述了Python生成不重復隨機值的方法。分享給大家供大家參考。具體分析如下:
這里從一列表中,生成不重復的隨機值
算法實現如下:
- import random
- total = 100
- li = [i for i in range(total)]
- res = []
- num = 20
- for i in range(num):
- t = random.randint(i,total-1)
- res.append(li[t])
- li[t], li[i] = li[i], li[t]
- print res
其實python 已經實現這樣的方法:
- print random.sample(li, num)
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答