Home > Enterprise >  How would I randomly select one list from a list of lists?
How would I randomly select one list from a list of lists?

Time:04-28

I want to randomly select a list from a list of lists. When I've tried this on my own, my program returns all of the lists with matching items in that slot. Is there a way to narrow this down?

For example, if I put in "action" for mood, since it's in item slot[1], it returns the 3 animes with "action" in that slot. I also tried using random.choice() in my print function, but it only prints random items from each list that matches the mood input.

from random import choice

# create a list of animes
 animes = [['naruto', 'action', 'drama', 'series', 'comedy'],
           ['nagatoro', 'slice of life', 'comedy', 'series', 'romance'],
           ['one piece', 'action', 'comedy', 'series', 'drama'],
           ['netoge no yome', 'action', 'slice of life', 'series' 'comedy']
          ]

# input mood
print('What mood are you in?')
mood = input()
for item in animes:
    if item[1]==mood:
        print(mood    ' anime:'   item[0])

CodePudding user response:

Collect the action animes into a new list, and then pass that list into random.choice():

import random

selected_animes = [anime for anime in animes if anime[1] == 'action']

random.choice(selected_animes)

Sample output:

['netoge no yome', 'action', 'slice of life', 'seriescomedy']

CodePudding user response:

import random
random.choice(animes)

CodePudding user response:

import random

Listoflists = [list, list2, etc]
random.choices(Listoflists)

Print(listoflists)

#You can shuffle them too with:

random.shuffle(list,list2)

CodePudding user response:

I think this does what you want. It finds all the animes with a mood that matches what the user inputted, and then randomly selects one of them with the random.choice() function.

It also creates a set of possible moods that it uses to make sure the user inputs something that will match at least one of the anime in the list of lists.

from random import choice

# create a list of animes
animes = [['naruto', 'action', 'drama', 'series', 'comedy'],
          ['nagatoro', 'slice of life', 'comedy', 'series', 'romance'],
          ['one piece', 'action', 'comedy', 'series', 'drama'],
          ['netoge no yome', 'action', 'slice of life', 'series' 'comedy']
         ]

possible_moods = set(item[1] for item in animes)

# input mood
while True:
    mood = input('What mood are you in? ')
    if mood in possible_moods:
        break
    else:
        print('Sorry that is not a possible mood, try again.')

mood_matches = [item for item in animes if item[1] == mood]
selection = choice(mood_matches)
print(f'{mood} anime: {selection[0]}')

  • Related