如何不重复randint值 [英] how to not repeat randint value

查看:60
本文介绍了如何不重复randint值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚写了一个代码来生成随机数并尝试将其与随机数匹配,但我不知道如何不重复 randint 值,有人可以帮助我吗?

I just wrote a code to generate random numbers and try to match it with random numbers, but I don't know how to not repeat the randint value, can someone help me?

from random import randint
import time

first_time = time.ctime()
print  first_time

x = randint(1, 10000)
while x != randint(1, 10000):
    ran = randint(1, 10000)
    print ran
    x = ran

print 'You number is: ', x
print ('You stared at: '+first_time)
print ('You finished at: '+time.ctime())  
print('Finish')

推荐答案

最简单的可能是:

deck = list(range(1, 10001))
random.shuffle(deck)

并使用 deck.pop() 获得下一个randint 无需重复".

and use deck.pop() to get the next "randint without repetition".

这几乎就是如何从一副牌中获得一张不重复的随机牌(这确实是 random.shuffle 的名字所暗示的,以及为什么我将变量称为 deck>:-):你从牌堆中的所有牌开始,洗牌一次(当然是彻底!-),然后每次只处理牌堆顶部的最后一张牌,不要把它放回牌堆.

This is pretty much how you get a random card without repetition from a deck (which indeed the very name of random.shuffle suggests, and why I called the variable deck:-): you start with all cards in the deck, shuffle the deck once (thoroughly of course!-), then just deal the last card from the top of the deck each time, without putting it back in the deck.

这篇关于如何不重复randint值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆