我有一个嵌套列表,格式如下:
[['john'],['jack','john','mary'],['howard','john'],['jude']...]
我想找到嵌套列表中出现的john的前3个或5个索引(因为列表非常长)并返回如下索引: (0,0),(1,1),(2,1)或任何可取的格式。
我对嵌套列表很新。任何帮助将不胜感激。
答案 0 :(得分:4)
问题1 :这是使用嵌套理解列表的一种方法。然而,我会看看是否有傻瓜。
nested_list = [['john'],['jack','john','mary'],['howard','john'],['jude']]
out = [(ind,ind2) for ind,i in enumerate(nested_list)
for ind2,y in enumerate(i) if y == 'john']
print(out)
返回:[(0, 0), (1, 1), (2, 1)]
更新:此处发现的类似内容Finding the index of an element in nested lists in python。然而答案只取第一个值,可以转换成:
out = next(((ind,ind2) for ind,i in enumerate(nested_list)
for ind2,y in enumerate(i) if y == 'john'),None)
print(out) # (0,0)
问题2:(来自评论)
是的,将y == 'john'
编辑为:'john' in y
。
nested_list = [['john xyz'],['jack','john dow','mary'],['howard','john'],['jude']]
out = [(ind,ind2) for ind,i in enumerate(nested_list)
for ind2,y in enumerate(i) if 'john' in y]
print(out)
返回:[(0, 0), (1, 1), (2, 1)]
问题3:(来自评论)
获得前N个元素的最有效方法是使用像这样的pythons库itertools:
import itertools
nested_list = [['john xyz'],['jack','john dow','mary'],['howard','john'],['jude']]
gen = ((ind,ind2) for ind,i in enumerate(nested_list)
for ind2,y in enumerate(i) if 'john' in y)
out = list(itertools.islice(gen, 2)) # <-- Next 2
print(out)
返回:[(0, 0), (1, 1)]
这里也回答:How to take the first N items from a generator or list in Python?
问题3扩展:
现在说你想把它们放在N块中,然后你可以这样做:
import itertools
nested_list = [['john xyz'],['jack','john dow','mary'],['howard','john'],['jude']]
gen = ((ind,ind2) for ind,i in enumerate(nested_list)
for ind2,y in enumerate(i) if 'john' in y)
f = lambda x: list(itertools.islice(x, 2)) # Take two elements from generator
print(f(gen)) # calls the lambda function asking for 2 elements from gen
print(f(gen)) # calls the lambda function asking for 2 elements from gen
print(f(gen)) # calls the lambda function asking for 2 elements from gen
返回:
[(0, 0), (1, 1)]
[(2, 1)]
[]