2

对不起,如果这很明显,我很新。

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

#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()
4

4 回答 4

10

不要选择随机整数,而是随机排列列表并选择前两项:

import random

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

item1, item2 = choices[:2]

因为我们先打乱了一个可能的选择列表,然后选择了前两个,所以你可以保证item1并且item2永远不会彼此相等。

使用random.shuffle()使选项保持打开状态,以对剩余的选项进行操作;你这里只有 1 个,但在更大的集合中你可以继续挑选迄今为止尚未挑选的物品:

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个随机数而不重复。

如果您只需要一个 2 的随机样本,请random.sample()改用:

import random

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

item1, item2 = random.sample(choices, 2)
于 2013-09-10T15:18:46.983 回答
5

您可以使用randomPython 中的模块为您完成繁重的工作,特别是random.sample()

>>> import random
>>> random.sample(['candy', 'steak', 'vegetable'], 2)
['vegetable', 'steak']
于 2013-09-10T15:21:02.370 回答
0

如果你想保留原始逻辑,这里有一些伪代码:

while(P2Local == A)
   P2Local = random.randint(1,3)
于 2013-09-10T15:25:29.643 回答
0
from random import choice
x = ['foo','bar','fight']
num_uniq = 2
uniq_rand = set()
while len(uniq_rand) < num_uniq:
  uniq_rand.add(choice(x))
print uniq_rand

正如@Martijn 指出的那样,这肯定不如random.sample()=)

于 2013-09-10T15:26:03.280 回答