Is it possible to search for a string in an array that is in a larger array?
I have an array that contains arrays of either one, two, three, or four strings.

for instance:
myList[1] =
myList[2] =

I want to search for 'sheep'
Is that possible?

Thanks for your time and consideration

Recommended Answers

All 10 Replies

If you knew that the array is only two deep (2D array) then you could do it:

for listIndex, subList in enumerate(myList):
    try:
        ind = subList.index('sheep')
        break
    except ValueError:
        print "Not in list number",listIndex
print "It is in list number",listIndex
print "and index number",ind,"of that list"

What that does is it goes through all the lists inside your larger list, looks for the string and if it finds the string it breaks from the loop and gives the two values, one is the list that it is in inside the larger list (from 0) and the other is the index of the string in that sublist.

hope that helps :)

Thanks for the help! really appreciated :D

Though I can't seem to get it to work with my entire program. Could you look at my code? I placed your code but also added a loop, since my assignment requires me to print out all matching items. I might have screwed it up somewhere along the lines.

The brief is to have a user input a tab-delimited text file and be able to search either by author or journal to find a paper. everything works fine when i search for a paper through a journal, but i can't get it to work when I search by author (and I think its because of the array is two deep).

This is an example text file that will be used:

a3-example-data.txt

And here is my code:

from string import *

while True:
inputfile = raw_input("Input filename: ")
try:
openfile = open(inputfile, "r")
break
except:
print "Invalid file. Please enter a correct file."

tempAuthorsList = []
journalsList = []
authorsList = []
papersList = []

#

This is to parse the data into separate lists

#
for rec in openfile:
rec = rec.strip() ## strip off newline
substrs = rec.split("\t")
if len(substrs) > 3: ## blank or incomplete records
tempAuthorsList.append(substrs[0])
papersList.append([substrs[1], substrs[2]])
journalsList.append(substrs[3])

#

This is to split items in the author list that have more than one name

#
for line in tempAuthorsList:
names = line.split(";")
authorsList.append(names)

openfile.close()

def authorNameOutput(names):
"""This function is to separate author names for print appropriately
depending on how many author names are within the index"""
for name in names:
if "," in name:
sepchar = "& "
break
else:
sepchar = ", "

n = len(names)
if n == 0:
return ""
elif n == 1:
return names[0]
elif n == 2:
return " & ".join(names)
return "%s%s& %s" % (sepchar.join(names[:-1]), sepchar, names[-1])

def search(dataList, string):
"""This is the search function that searches the defined
string within its respective list"""
print "\n"
print "Search results:"
i = -1
for value in dataList:
try:
while 1:
i = dataList.index(string, i+1)
print authorNameOutput(authorsList[i]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
break
except ValueError:
print "\n Please search again"
break

def searchAuthor(dataList, string):
print"\n"
print"Search results:"
i = -1
for listIndex, subList in enumerate(dataList):
try:
ind = subList.index(string, i+1)
print authorNameOutput(authorsList[listIndex]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
break
except ValueError:
print "\n Please search again"
break

#

Command prompt for users to execute a search

#
while True:
searchCommand = raw_input("\n To search a paper by: \n Author press (a) \n Journal/Conference press (j) \n Or to exit press (q): ")
if searchCommand == "a":
searchInput = raw_input("Type the name of the author(s): ")
searchAuthor(authorsList, searchInput)
elif searchCommand == "j":
searchInput = raw_input("Type the name of the journal: ")
search(journalsList, searchInput)
elif searchCommand == "q":
print "\n Closing program"
else:
print "\n Unknown command"

Sorry if this is overwhelming.. appreciate any help though!
cheers!

You should not be using "string" as a variable name as it is used by Python. Also, "i", "l" and "o" are not good choices for single letter variable names as they can look like numbers. Test each function individuallty and see comments in the code.

def searchAuthor(dataList, string):
   print"\n"
   print"Search results:"
   i = -1
   for listIndex, subList in enumerate(dataList):
      try:
         ind = subList.index(string, i+1)

         ##   test for a successful find, -1 == not found
         if ind > -1:

             ## you are searching through subList but sending 
             ## authorsList to the print function
             ## Make sure they are properly aligned
             print authorNameOutput(authorsList[listIndex]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
             break
      except ValueError:
         print "\n Please search again"
         break 
##
##-----------------------------------------------------------------------------
def search(dataList, string):
   """This is the search function that searches the defined
      string within its respective list"""
   print "\n"
   print "Search results:"
   i = -1
   for value in dataList:
      try:

         ##   while loop is not necessary and is an
         ##   infinite loop that will only stop if string is found
         while 1:

            ## do you want to look in dataList or value?
            ind = dataList.index(string, i+1)

            ##   same thing here
            if ind > _1:

                ## you are searching through dataList but sending 
                ## authorsList to the print function
                print authorNameOutput(authorsList[i]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
                break
      except ValueError:
         print "\n Please search again"
         break

Thanks for the help!

Though I don't quite follow, I tried adding in where you had edited.. but it doesn't seem to work still.

For future reference,

You can do something like this for multi-level lists

def find_item(iterable,obj):
    if hasattr(iterable,"__iter__"):
        for item in iterable:
            if item == obj or find_item(item,obj): return True
    return False

find_item([1,2,["a",["b",2,[3,"asdf"]],3]],"asdf") #returns True

or you can just flatten the list

I tried adding in where you had edited.. but it doesn't seem to work still.

Test each function individually and post what "doesn't work" means for each individual function.

This would be a simple search in a nested list, but this approach has certain caveats ...

mylist = [['dog', 'cat'], ['lizard', 'sheep', 'pig']]
print( "'sheep'" in str(mylist) )  # True

I think from previous thread that only knowing existence of element is not enough in this case. here is some searching example in 2d:

yList = [['dog', 'cat']]
myList.append( ['lizard', 'sheep', 'pig'])
print myList
for i,li in enumerate(myList):
    if 'sheep' in li:
        print 'sheep list is list %i:'%i,li
        print "Position of 'sheep' there is", li.index('sheep')

I think from previous thread that only knowing existence of element is not enough in this case. here is some searching example in 2d:

yList = [['dog', 'cat']]
myList.append( ['lizard', 'sheep', 'pig'])
print myList
for i,li in enumerate(myList):
    if 'sheep' in li:
        print 'sheep list is list %i:'%i,li
        print "Position of 'sheep' there is", li.index('sheep')

THANKS THIS SOLVED MY ISSUE!!! :)
Thanks for all the help on this thread. couldn't have wrote my program without all the help

Cheers

Ok. You are welcome. Close the thread, please.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.