换句话说,如果发现“f”位于子列表的第4个位置,则返回该子列表,否则,如果未找到“f”,则将其排除。
List = [['a','b','c','d','f'],['a','b','c','d','e'],['a','b','c','d','e'],['a','b','c','f','f'],['a','b']]
如果所有子列表大小相同,我有以下功能。
def Function(SM):
return filter(lambda x: re.search("f",str(x[4])),List)
IndexError: list index out of range
Desired_List = [['a','b','c','d','f'],['a','b','c','f','f']]
由于速度和效率成本的原因,我不愿意使用for循环。有没有其他选择同样快?
答案 0 :(得分:1)
您可以使用列表理解:
lst = [['a','b','c'], ['a','b','c','d','f'],['a','b','c','d','e'],['a','b','c','d','e'],['a','b','c','f','f'],['a','b']]
lst_desired = [l for l in lst if len(l) >= 5 and l[4] == "f"]
print lst_desired
输出
[['a', 'b', 'c', 'd', 'f'], ['a', 'b', 'c', 'f', 'f']]
答案 1 :(得分:1)
>>> li=[['a','b','c','d','f'],['a','b','c','d','e'],['a','b','c','d','e'],['a','b','c','f','f'],['a','b']]
>>> filter(lambda l: l[4:5]==['f'], li)
[['a', 'b', 'c', 'd', 'f'], ['a', 'b', 'c', 'f', 'f']]