这是您可以做到的基本方法。这使用了所谓的列表推导的概念,以便以有效的方式生成列表。.format()
表示字符串格式,它允许您将变量传递到各种格式的字符串中(此处的文档,但现在只知道{0}
指的是 的第一个参数format()
)。
names
使用上述列表推导生成,它在语法上等价于:
names = []
for i in range(6):
names.append(raw_input('Enter a name: ')
此模式稍后用于生成您的列表,而无需杀手或先前的猜测。很高兴解释任何没有意义的部分(感谢@JonClements 指出我留下的一些奇怪之处):
import random
# Choose your names
names = [raw_input('Enter killer name: ') for i in xrange(6)]
# Choose a killer
killer = random.choice(names)
# Run for as many times as you want (here we do 6; could also be len(names)
max_guesses = 6
for guessno in xrange(max_guesses):
guess = raw_input('Guess the killer: ')
# If the guess is not the killer...
if guess != killer:
# This line creates a list that does not include the killer nor the guess
hint = random.choice([n for n in names if n not in [killer, guess]])
print 'Hint, the killer is not {0}'.format(hint)
else:
print 'Correct! The killer is {0}'.format(guess)
break