简体   繁体   English

如何在已分配了随机数的列表中打印单词?

[英]How to print a word in a list which has been assigned a random number?

I was wondering if anyone could help me with this problem. 我想知道是否有人可以帮助我解决这个问题。 In my piece of code that I am working on, I am creating a game upon which the user guesses a word from the list imported from a text file in python 3.3. 在我正在编写的代码段中,我正在创建一个游戏,用户可以在该游戏中从python 3.3的文本文件导入的列表中猜一个单词。 I choose a random word from the list eg 我从列表中选择一个随机词,例如

words = random.randint(0,len(wordlist))

I have successfully, got the program working, however when the user gets the word wrong, it prints the random number its assigned to not the word from the list. 我已经成功完成了该程序的工作,但是当用户输入错误的单词时,它将打印分配给该单词的随机数,而不是列表中的单词。 for example 例如

else:
    print("No, the answer was",words)

I was wondering how to get to print the word from the list not the random number? 我想知道如何从列表而不是随机数字打印单词?

Don't use a random number at all. 完全不要使用随机数。 Use the random.choice() function instead: 请改用random.choice()函数

words = random.choice(wordlist)

random.choice() picks a random item from the list. random.choice()从列表中选择一个随机项目

Your use of random.randint() has two problems: 您对random.randint()有两个问题:

  1. You now need to always use wordlist[words] each time you want the word; 现在,您每次需要wordlist[words]必须始终使用wordlist[words] you are never really interested in random integer, so there is no point in storing that. 您对随机整数从未真正感兴趣,因此存储该整数毫无意义。 But

     words = wordlist[random.randint(0, len(wordlist))] 

    is rather more verbose than the random.choice() alternative. random.choice()更冗长。

  2. random.randint() picks a number between the start and stop values, inclusive . random.randint()在起始值和终止值( 包括 random.randint()之间选择一个数字。 That means you can end up picking exactly len(wordlist) , but there is no such index in your wordlist list; 这意味着您最终可以精确地选择len(wordlist) ,但您的wordlist表列表中没有这样的索引; you'd get an IndexError . 你会得到一个IndexError You need to use random.randint(0, len(wordlist)) - 1 , really, or perhaps random.randrange(len(wordlist)) instead. 您需要使用random.randint(0, len(wordlist)) - 1 ,或者实际上是使用random.randrange(len(wordlist))代替。

    But again, random.choice() is just easier. 但同样, random.choice()更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM