![](/img/trans.png)
[英]Find index of element in sublist that is same across all the sublists in a nested list
[英]How do you remove a sublist if a certain element is not found at a specific position across all sublists?
換句話說,如果發現“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循環。 有沒有其他同樣快速的選擇?
您可以使用列表理解:
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']]
>>> 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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.