Nikita Gupta Nikita Gupta - 1 year ago 76
Python Question

One line python code to return all sublists of list containing specific substring in a particluar column

I want to return all the sublists of lists which contains specific substring in a particular column:

For eg:


Search Criteria : Return all sublists which contains substring 2005 at the 2nd index .

Output :


I tried using :

matching = [s for s in List if "2005" in s[1]]

but it returns:


Answer Source

Your list comprehension approach is good and gives the correct result. Are you sure your code is the same from which you pasted the output because it works for me:

>>> List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
>>> [sublist for sublist in List if '2005' in sublist[1]]
[['2006ab', '2005ac'], ['2006ab', '2005ac'], ['2006ab', '2005ac']]

which is same as what you desire.

If you are looking for an alternative, you may use filter()

>>> filter(lambda x: '2005' in x[1], List)
[['2006ab', '2005ac'], ['2006ab', '2005ac'], ['2006ab', '2005ac']]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download