Reputation: 29
I am trying to do a search function for a 2 dimension array or list. How do I search thru this list and return the values of the items.
myfoodlist = [("Chicken Pasta", 10),("Beef Noodle", 12),("Hot Coffee", 4.20),( "Fish and Chips", 8.50)]
foodsearch = raw_input("Please input food to search: ")
for item in (myfoodlist) :
if item.find(foodsearch) != -1:
searchReturnsItems.append(item)
for item in searchReturnsItems:
print(item, "\t:\t")
searchReturnsItems.clear()
Example
I like to ask for a key word like "beef" and return a list of all beef items and store in array.
Above is my code and I have some challenges.
Anyone can provide me an example to search a 2D array will be helpful
Upvotes: 0
Views: 70
Reputation: 345
myfoodlist = [("Chicken Pasta", 10),("Beef Noodle", 12),("Hot Coffee", 4.20),( "Fish and Chips", 8.50)]
foodsearch = input("Please input food to search: ")
def searchFood():
for item in (myfoodlist) :
if(item[0]==foodsearch):
return item[0],item[1]
searchFood()
output
Please input food to search: Hot Coffee
Out[2]: ('Hot Coffee', 4.2)
Upvotes: 0
Reputation: 522
I've slightly modified your searching method to use list comprehension, and use re
package to support partial case insensitive searches.
import re
myfoodlist = [("Chicken Pasta", 10),("Beef Noodle", 12),("Hot Coffee", 4.20),( "Fish and Chips", 8.50)]
foodsearch = input("Please input food to search: ")
searchReturnsItems = [item for item in myfoodlist if re.search(foodsearch, item[0], re.IGNORECASE)]
for item in searchReturnsItems:
print(item, "\t:\t")
searchReturnsItems.clear()
Output
Please input food to search: beef
('Beef Noodle', 12)
Upvotes: 1