Home > Net >  Choosing something from a 2D array based on an input
Choosing something from a 2D array based on an input

Time:06-30

I have a 2d array that I want the program to search from.

HabitatGroups = [["amethyst","silver","crystal","copper","red"],#mountain/hill
                 ["black","gold","green"],#swamp/forest
                 ["amethyst","blue","bronze","gold","topaz"],#water adjacent
                 ["blue","brass","copper"],#warm dry
                 ["white","crystal","silver"],#cold
                 ["sapphire","emerald","crystal","amethyst","blue"]]#underground

x=input("Choose a type of dragon")

Basically, I want the program to take x and use it to randomly select from all the lists that x is in. Say x is "silver", the program would search the mountain/hill and cold sections of the array, and randomly select a different option. How would I go about doing that?

CodePudding user response:

One possible solution is to use random.choice:

import random

HabitatGroups = [
    ["amethyst", "silver", "crystal", "copper", "red"],  # mountain/hill
    ["black", "gold", "green"],  # swamp/forest
    ["amethyst", "blue", "bronze", "gold", "topaz"],  # water adjacent
    ["blue", "brass", "copper"],  # warm dry
    ["white", "crystal", "silver"],  # cold
    ["sapphire", "emerald", "crystal", "amethyst", "blue"], # underground
]


x = input("Choose a type of dragon: ")

sample = set()
for g in HabitatGroups:
    if x in g:
        for v in g:
            if v != x:
                sample.add(v)

print(random.choice(list(sample)) if len(sample) > 0 else "Not Found")

Prints (for example):

Choose a type of dragon: silver
crystal

If the input is not found in HabitatGroups it prints Not Found.

Note: Consider to use sets instead of lists in HabitatGroups to speed up the creation of sample list.

  • Related