I'm currently writing a test code for a project which takes the ingredients in your fridge and runs it over the recipes, and prints out the recipes that have your ingredients.
But I'm a bit frustrated because no matter how hard I try, the result wouldn't match. Here's a test run.
ingre = 'đùi gà, hành lá'
content = 'dvjkshdvjkdsnvjksuihv đùi gà, djghajhdjfkasjkd Hành lá'
ingres= ingre.split(',')
content_list = content.split(',')
print(ingres)
print(content)
index = content_list.index('đùi gà')
print('Vị trí của công thức chứa đùi gà là', index)
Even though it should print out the 'dvjkshdvjkdsnvjksuihv đùi gà', but instead the program displays
ValueError: 'đùi gà' is not in list
Can someone help me understand why is it not working?
CodePudding user response:
You are Finding an index of 'đùi gà' as an element in your content_list. but content_list contains ['dvjkshdvjkdsnvjksuihv đùi gà', ' djghajhdjfkasjkd Hành lá'] that's why it displays ValueError: 'đùi gà' is not in the list.
CodePudding user response:
Example among many others if you want to get the index of the ingredient if he's on the list of recipees:
ingredient = "dui ga, hanh la"
ingres= ingredient.split(',')
content = 'dvjkshdvjkdsnvjksuihv dui ga,djghajhdjfkasjkd hanh la'
content_list = content.split(',')
print(ingres)
print(content_list)
searching = "dui ga"
for item in content_list:
if searching in item:
print("index -> ", content_list.index(item))
CodePudding user response:
def find_index_of_string_from_list_of_strings(search_string, content_list):
i = 0
for string in content_list:
if string.index(search_string) >= 0:
return i
i = 1
return -1
ingre = 'đùi gà, hành lá'
content = 'dvjkshdvjkdsnvjksuihv đùi gà, djghajhdjfkasjkd Hành lá'
ingres= ingre.split(',')
content_list = content.split(',')
print(ingres)
print(content)
index = find_index_of_string_from_list_of_strings('đùi gà', content_list)
print('Vị trí của công thức chứa đùi gà là', index)
As you are trying to get the substring searched within content_list which is a list of strings, creating a function like this should work...
