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]
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.
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())
would give you 100 random numbers without repeating.
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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…