Python finding a value in a list of lists

前端 未结 2 1566
南笙
南笙 2021-01-17 02:19

Recently I had to find which list something was in. I used:

def findPoint(haystack, needle): # haystack = [[1,2,3], [4,5]...,[6,7,8,9]]
    for x in range(le         


        
2条回答
  •  一整个雨季
    2021-01-17 03:02

    You could do something like this with a 1-liner:

    def find_point(haystack,needle)
        return next(elem for elem in haystack if needle in elem)
    

    I think should work (but it returns the haystack element). This raises a StopIteration if the needle isn't in any of the haystack elements.

    It doesn't sound like you actually need the index, but if you do, use enumerate (as proposed by the excellent answer by Dima Rudnik):

    def find_point(haystack,needle):
        return next(idx for idx,elem in enumerate(haystack) if needle in elem)
    

提交回复
热议问题