我正在尝试用 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.
需要 try ... except 来处理您想从空列表中获取一些食物的情况。
