问题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)]
问题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)]
问题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)]
[]