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

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!

Attachments
AUTHOR(S)	YEAR	TITLE	JOURNAL/CONFERENCE
Accot;Zhai	2001	Scale effects in steering law tasks	Proc. ACM CHI
Acredolo	1977	Developmental Changes in the Ability to Coordinate Perspectives of a Large-Scale Space	Developmental Psychology
Aginsky;Harris;Rensink;Beusmans	1997	Two strategies for learning a route in a driving simulator	Journal of Environmental Psychology
Agrawala;Beers;Frohlich;Hanrahan;McDowall;Bolas	1997	The two-user responsive workbench: Support for collaboration through individual views of a shared space	Proc. ACM SIGGRAPH
Ahmadabadi;Eiji	1996	Cooperation strategy for a group of object lifting robots	Proc. of IROS
Ahuja;Webster	2001	Perceived disorientation: An examination of a new measure to assess web design effectiveness	Interacting with Computers
Albers;Bergman	1995	The audible Web: Auditory enhancements for Mosaic	Proc. ACM CHI
Aldestein;Ellis	1993	Effect of Head-Slaved Visual Image Roll on Spatial Situation Awareness	Proc. HFES
Alexander;Wickens	2001	"Cockpit display of traffic information: The effects of traffic load, dimensionality, and vertical profile orientation"	Proc. HFES
Alfano;Michel	1990	Restricting the field of view: perceptual and performance effects	Perceptual and Motor Skills
Allen;Ondracek	1995	Age-sensitive cognitive abilities related to children's acquisition of spatial knowledge	Developmental Psychology
Allen;Siegel;Roninski	1978	The Role of Perceptual Context in Structuring Spatial Knowledge	Journal of Experimental Psychology: Human Learning and Memory
Allen;Singer	1997	Landmark detection and distance estimation in large scale virtual environments	Proc. HFES
Amazeen;Turvey	1996	Weight perception and the haptic size-weight illusion are functions of the inertia tensor	Journal of Experimental Psychology: Human Perception and Performance
Angelaki;Shaikh;Green;Dickman	2004	Neurons compute internal models of the physical laws of motion	Nature
Anonymous	1993	Technical correspondance - Random Number Generators	Communications of the ACM
Anonymous	1992	Research Directions in Virtual Environments (NSF Invitational Workshop)	Computer Graphics
Anonymous	1998	"Exploring sequential data: Commentary on Bowers, Jentsch, Salas, and Braun (1998)"	Human Factors
Arai;Ota	1996	Let us work together - Task planning of multiple mobile robots	Intelligent Robots and Systems
Aretz	1991	The Design of Electronic Map Displays	Human Factors
Arnold;Farrell;Pettifer;West	2002	Performance of a skilled motor task in virtual and real environments	Ergonomics
Arthur;Booth;Ware	1993	Evaluating 3D Task Performance for Fish Tank Virtual Worlds	ACM Transactions on Information Systems
Authier;Lortie;Gagnon	1996	Manual handling techniques: Comparing novices and experts	International Journal of Industrial Ergonomics
Authur;Hancock;Chrysler	1993	Spatial orientation in Real and Virtual Worlds	Proc. HFES
Avraamides;Klatzky;Loomis;Golledge	2004	use of cognitive versus perceptual heading during imagined locomotion depends on the response mode	Psychological Science
Aytes	1996	Comparing collaborative drawing tools and whiteboards: An analysis of the group process	Computer Supported Cooperative Work
Badler;Hollick;Granieri	1993	Real-time control of a virtual human using minimal sensors	Presence: Teleoperators and Virtual Environments
Badler;Palmer;Bindiganavale	1999	Animation control for real-time virtual humans	Communications of the ACM
Bailenson;Blascovich;Beall;Loomis	2001	Equilibrium theory revisited: Mutual gaze and personal space in virtual environments	Presence: Teleoperators and Virtual Environments
Baird;Wagner;Noma	1982	Impossible cognitive spaces	Geographical Analysis
Bajura;Fuchs;Ohbuchi	1992	Merging virtual objects with the real world: Seeing ultrasound imagery within the patient	Proc. ACM SIGGRAPH
Bakker;Werkhoven;Passenier	1999	The effects of proprioceptive and visual feedback on geographical orientation in virtual environments	Presence: Teleoperators and Virtual Environments
Bakker;Werkhoven;Passenier	2001	Calibrating visual path integration in VEs	Presence: Teleoperators and Virtual Environments
Balakrishnan;Hinckley	2000	Symmetric bimanual interaction	Proc. ACM CHI
Balakrishnan;Kurtenbach	1999	Exploring bimanual camera control and object manipulation in 3D graphics interfaces	Proc. ACM CHI
Balcisoy;Thalmann	1998	Hybrid approaches to interactions between real and virtual humans in mixed environments	Proc. EGVE
Banks	1992	Interactive Manipulation and Display of Two-Dimensional Surfaces in Four- Dimensional Space	Proc. ACM I3D
Banon	1990	Implementation and extension of the ladder algorithm	Proc. IEEE International Conference on Robotics and Automation
Bardram	2000	Temporal coordination: On time and coordination of collaborative activities at a surgical department	Computer Supported Cooperative Work
Bardy;Oullier;Bootsma;Stoffregen	2002	Dynamics of human postural transitions	Journal of Experimental Psychology: Human Perception and Performance

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

Edited 6 Years Ago by woooee: n/a

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

Edited 6 Years Ago by jcao219: n/a

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

This question has already been answered. Start a new discussion instead.