I'm trying to figure out how to index substrings of a list. Say we're given the list:
shoes = ['Oxford shoes', 'Casual shoes', 'Tennis shoes', 'Oxford
shoes']
For indexing a normal list I would do (assigned variable)[index value]. So for this case, if I wanted to find where 'Casual shoes' fell under the list shoes, I would do:
shoes[1] or shoes[-3]
But how would I index say the word 'Casual' in the substring 'Casual shoes' of the list shoes?
To find the index of the string containing a substring you can use:
casual_index = shoes.index(next(w for w in shoes if 'Casual' in w))
This returns: 1
Then you can split it to get the word as @Thom mentioned in their comment.
You can simply check if what you want is in the strings.
shoes = ['Oxford shoes', 'Casual shoes', 'Tennis shoes', 'Oxford shoes']
def find_index(elements, text):
results = []
for i, element in enumerate(elements):
if text in element:
results.append(i)
return results
print(find_index(shoes, "Casual"))
[1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.