尝试生成一系列唯一的随机数 [英] Trying to generate a series of unique random numbers

查看:74
本文介绍了尝试生成一系列唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这很明显,那是新的.

Sorry if this is obvious, im pretty new.

这是代码. 它绝不应该打印出我所理解的相同的两件事,但有时却可以.关键是p1为1应该防止p2为1,如果p2为1,则p2应该以相同的p1值再次运行,但是应该生成一个新的随机数.可能再次为1,但是函数应该继续返回else并运行,直到它们不同为止,对吗?

Here is the code. It should never print the same two things as i understand it, but it sometimes does. The point is that p1 being 1 should prevent p2 from being 1, and if p2 is 1, p2 should run again with the same p1 value, but should generate a new random number. It might be 1 again, but then the function should just keep returning else and running until they're different, right?

#Random Test with Exclusion
P1Item = 'Empty'
P2Item = 'Empty'
import random
import time

def P1():
    global P1Item
    global P2Exclusion
    P1Local = random.randint(1,3)
    if P1Local == 1:
        P1Item = 'Candy'
        P2(P1Local)
    elif P1Local == 2:
        P1Item = 'Steak'
        P2(P1Local)
    elif P1Local == 3:
        P1Item = 'Vegetables'
        P2(P1Local)


def P2(A):
    global P2Item
        P2Local = random.randint(1,3)
        if P2Local == 1 and A != 1:
            P2Item = 'Candy'
        elif P2Local == 2 and A != 2:
            P2Item = 'Steak'
        elif P2Local == 3 and A != 3:
        P3Item = 'Vegetables'
        else:
            B = A
            P2(B)

def Test():
    print('Test')
    print('Define')
    P1()
    print(P1Item + ' ' + P2Item)
    time.sleep(1)
    input()
    Test()

Test()

推荐答案

而不是选择随机整数,而是随机排列 list 并选择前两个项目:

Instead of picking random integers, shuffle a list and pick the first two items:

import random

choices = ['Candy', 'Steak', 'Vegetables']
random.shuffle(choices)

item1, item2 = choices[:2]

因为我们首先对可能个选择进行了混排,然后选择了前两个,所以可以保证item1item2永远不相等.

Because we shuffled a list of possible choices first, then picked the first two, you can guarantee that item1 and item2 are never equal to one another.

使用 random.shuffle() 可以使该选项处于打开状态剩下的选择;您这里只有1个,但是在更大的集合中,您可以继续选择到目前为止尚未选择的项目:

Using random.shuffle() leaves the option open to do something with the remaining choices; you only have 1 here, but in a larger set you can continue to pick items that have so far not been picked:

choices = list(range(100))
random.shuffle(choices)
while choices:
    if input('Do you want another random number? (Y/N)' ).lower() == 'n':
        break
    print(choices.pop())

将为您提供100个随机数字,而无需重复.

would give you 100 random numbers without repeating.

如果您需要的只是2个随机样本,请使用 代替:

If all you need is a random sample of 2, use random.sample() instead:

import random

choices = ['Candy', 'Steak', 'Vegetables']

item1, item2 = random.sample(choices, 2)

这篇关于尝试生成一系列唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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