Python finding a value in a list of lists

前端 未结 2 1565
南笙
南笙 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 02:55

    Yes, no need for range, for starters

    for hay in haystack:
      if needle in hay:
        return hay
    

    And if you really really need the index, use enumerate

    for x, hay in enumerate(haystack):
      if needle in hay:
        return x
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题