在python中从数组中选择随机词
有没有一种方法可以让我创建一个单词数组,然后从该数组中选择一个随机单词,然后在python中声明该数组中随机单词的第一个字母?您可以使用randint获得列表的随机索引在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"
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