Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中从数组中选择随机词_Python - Fatal编程技术网

在python中从数组中选择随机词

在python中从数组中选择随机词,python,Python,有没有一种方法可以让我创建一个单词数组,然后从该数组中选择一个随机单词,然后在python中声明该数组中随机单词的第一个字母?您可以使用randint获得列表的随机索引 your_list = ['Hello','world'] from random import randint print(your_list[randint(0,len(your_list)-1)]) 例如: from random import choice my_list = ["apples", "oranges"

有没有一种方法可以让我创建一个单词数组,然后从该数组中选择一个随机单词,然后在python中声明该数组中随机单词的第一个字母?

您可以使用randint获得列表的随机索引

your_list = ['Hello','world']
from random import randint
print(your_list[randint(0,len(your_list)-1)])
例如:

from random import choice

my_list = ["apples", "oranges", "pears"]
print(choice(my_list)[0])
嗨,我希望这有帮助

words = ['Random', 'Words', 'hello'] #Creating a list
from random import choice # importing choice 
random_letter = choice(words)[0] #getting the random word and then getting the first letter by indexing
print(random_letter)# printing output

那不行。。。它需要打印出来。如果你解释一下你提供的代码是如何回答这个问题的,这将是一个更好的答案。@reznik,这确实有效。@pppery,我补充了一些说明,谢谢你的建议。
# Import the random module
import random 

# Choose a random word from your list
randomWord = random.choice(your_list)

# Print that random word but only the first letter, which is done by adding the [0] at the end. 
print(randomWord[0])
words = ['Random', 'Words', 'hello'] #Creating a list
from random import choice # importing choice 
random_letter = choice(words)[0] #getting the random word and then getting the first letter by indexing
print(random_letter)# printing output