Выбор случайного слова из массива в python - PullRequest
0 голосов
/ 16 июня 2020

Есть ли у меня способ создать массив слов, затем выбрать случайное слово из этого массива, а затем указать первую букву этого случайного слова из указанного массива в python?

Ответы [ 4 ]

1 голос
/ 16 июня 2020
from random import choice

choice(your_list)

пример:

from random import choice

my_list = ["apples", "oranges", "pears"]
print(choice(my_list)[0])
1 голос
/ 16 июня 2020

Вы можете randint, чтобы получить случайный индекс для списка

your_list = ['Hello','world']
from random import randint
print(your_list[randint(0,len(your_list)-1)])
0 голосов
/ 16 июня 2020

Привет, надеюсь, это поможет.

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
0 голосов
/ 16 июня 2020
# 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])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...