Search a list using a string
numpy, python
Solution
Simple and straight
elem = 'why'
index_li = []
for idx, item in enumerate(A):
for word in item:
if word.startswith(elem):
index_li.append(idx)
break
print index_li
Example
>>> elem = 'wh'
... index_li = []
... for idx, item in enumerate(A):
... for word in item:
... if word.startswith(elem):
... print word, item
... index_li.append(idx)
... break
... print index_li
where ['where', 'what', 'when', 'how']
where ['tweet', 'where', 'why', 'how']
[1, 3]
Problem
I have a List of Lists: ``` A = [['andy', 'dear', 'boy', 'tobe', 'todo'], ['where', 'what', 'when', 'how'], ['korea', 'japan', 'china', 'usa'], ['tweet', 'where', 'why', 'how']] ``` I have three questions to be exact: - How do I retrieve a sub-list from this list using a particular element as a keyword? For instance, I want to retrieve all the lists having element 'why' in them? What is the best possible way of doing so? - How do I retrieve a sub-list from this list using a part of a particular element as a keyword? For instance, I want to retrieve all the lists having elements containing 'wh' as beginning characters of any of the elements? - How do I get the position or index of resulting sub-lists from any of these two searching methods? I am familiar with the concept of retrieving all the elements from a list with matching with a particular keyword, but its confusing when it comes to retrieve all the lists matching a particular keyword... Any guesses? Thanks in advance.