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:
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.
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]
I love list comprehensions and functional programming, so here's that approach
A
sub_list_a = [ el for el in A if 'why' in el ]
B
sub_list_b = [ el for el in A if any( ['wh' in s for s in el] ) ]
A little more difficult to read, but concise and sensible.
C
Then to get the indices of where each of the sub_lists were found
location_a = [ ii for ii, el in enumerate(A) if el in sub_list_a ]
Simply replace b
for a
to get the locations for part b.
For first:
>>> for l in A:
... if 'why' in l:
... print l
...
['tweet', 'where', 'why', 'how']
For the second:(wy any where)
>>> for l in A:
... for i in l:
... if 'wh' in i:
... print l
... break
...
['where', 'what', 'when', 'how']
['tweet', 'where', 'why', 'how']
to test at beginning try this: (using startswith() from @Harido)
>>> for l in A:
... for i in l:
... if i.startswith('wh'):
... print l
... break
...
['where', 'what', 'when', 'how']
['tweet', 'where', 'why', 'how']
For third:
To find index, you can use A.index(l)
method after print stamens for example:
>>> for l in A:
... for i in l:
... if 'wh' in i:
... print l
... print A.index(l)
... break
...
['where', 'what', 'when', 'how']
1
['tweet', 'where', 'why', 'how']
3
But remember I am not good in Python. Some one can give you better ways. (I am writing C like code that is poor) I would like to share this link: Guido van Rossum
Edit:
thanks to @Jaime to suggesting me for k, l in enumerate(A):
>>> for k, l in enumerate(A):
... for i in l:
... if 'wh' in i:
... print l
... print "index =", k
... break
...
['where', 'what', 'when', 'how']
index = 1
['tweet', 'where', 'why', 'how']
index = 3
For all the answers combined:
mylist = [['andy', 'dear', 'boy', 'tobe', 'todo'], ['where', 'what', 'when', 'how'], ['korea', 'japan', 'china', 'usa'], ['tweet', 'where', 'why', 'how']]
for num, sublist in enumerate(mylist):
if 'why' in sublist:
print sublist
for ele in sublist:
if ele.startswith('wh'):
print ele, num
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With