我正在尝试在Python中创建一个小程序,该程序从列表中选择一个随机字符串并打印该字符串。但程序通常会两次选择相同的字符串。
有没有办法确保每个字符串只输出一次?
到目前为止我的代码:
from random import choice
food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange']
print 'You should eat today :' + choice(food)
print 'You should eat tomorrow :' + choice(food)
如果您不关心之后列表的顺序,您可以先打乱列表,然后再迭代它。
import random
food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange']
random.shuffle(food)
for f in food:
print f
如果您不需要立即使用所有这些,则应在需要时弹出一个项目(这将耗尽列表)。
import random
food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange']
random.shuffle(food)
try:
print food.pop()
except IndexError:
print "No more food left!"
# ....
# some more code
# I'm hungry!
try:
print food.pop()
except IndexError:
print "No more food left!"
# etc.
尝试...除非需要处理您想从空列表中获取一些食物的情况。
today = choice(food)
tomorrow = today
while tomorrow == today:
tomorrow = choice(food)
print 'You should eat today : {}'.format(today)
print 'You should eat tomorrow : {}'.format(tomorrow)
代替 choice
,请使用 sample
:
today, tomorrow = random.sample(food, 2)
从文档中:
random.sample(population, k)
返回从
population
序列中选择的唯一元素的k
长度列表。用于随机抽样,无需更换。
我会使用random.sample
:
>>> from random import sample
>>> food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange']
>>> sample(food, 2)
['banana', 'blueberry']
>>> sample(food, 2)
['orange', 'apple']
>>> today, tomorrow = sample(food, 2)
>>> today
'banana'
>>> tomorrow
'blueberry'
如果您不关心在此过程中销毁列表,则可以使用此函数而不是选择。
import random
def del_choice(food):
if food:
return food.pop(random.randrange(len(food)))
return None
您可以尝试这种技术。这样,您可以一次打印一个列表中的所有元素,一次只能打印一次。只需将已打印的列表附加到新列表中,对两个列表进行排序,然后匹配两个列表的列表元素或长度。无论哪种方式,如果两个列表在元素或纵向上匹配,则打破无限循环!
from random import choice
q = 0
k = []
food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange']
food.sort()
while True:
i = choice(food)
if i in k:
pass
else:
print('You should eat today :' + i)
k.append(i)
k.sort()
q += 1
if k == food:
break