简体   繁体   English

一行python代码可返回特定列中包含特定子字符串的列表的所有子列表

[英]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: 例如:

List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]

Search Criteria : Return all sublists which contains substring 2005 at the 2nd index . 搜索条件:返回所有在第二索引处包含子字符串2005的子列表。

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()

>>> filter(lambda x: '2005' in x[1], List)
[['2006ab', '2005ac'], ['2006ab', '2005ac'], ['2006ab', '2005ac']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM