Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching Python Lists

ok, i have this code:

colors = ["Red" , "Green" , "Blue" , "Pink" , "Purple" , "Cyan"]

search = str(raw_input())

found = "not"

if search in colors:
    print "Found!"
else:
    print "not Found"

so far, it can find one item in a list only if you type the string in the terminal exactly as it is in the list, that is the problem.

i need to be able to type one or two characters in the terminal and have it so that it lists the strings inside the list that matches the search (for example: if i were to type "P" the terminal, it would list "Pink" and "Purple" because they match my search so far, but not exactly)

I may be overlooking something but, is there a way i can search a list this way without having to have over 200 lines of code (200+ lines because what i need to implement this to has over 150 strings in the list) just for searching for the string?

like image 872
Roger Parish III Avatar asked Dec 07 '22 08:12

Roger Parish III


2 Answers

The simplest way, using a list comprehension:

matches = [color for color in colors if color.startswith(search)]

If you have a large list this might not perform so well.

like image 122
Peter Graham Avatar answered Dec 13 '22 07:12

Peter Graham


What you need is a proper data structure. From your requirement description, I think trie is just the one.

You build a trie with a list of colors and then search the trie with user inputs (prefix is allowed). You can find diverse implementations on github or implement it yourself. :)

like image 32
Summer_More_More_Tea Avatar answered Dec 13 '22 06:12

Summer_More_More_Tea