I want to return all the sublists of lists which contains specific substring in a particular column:
For eg:
List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
Search Criteria : Return all sublists which contains substring 2005 at the 2nd index .
Output :
[["2006ab","2005ac"],["2006ab","2005ac"],["2006ab","2005ac"]]
I tried using :
matching = [s for s in List if "2005" in s[1]]
but it returns:
[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2005ac"]]
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']]
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.