2012-12-17 61 views
0

列表最近我只好找哪个列表的东西是我用:Python中找到一个值列表

def findPoint(haystack, needle): # haystack = [[1,2,3], [4,5]...,[6,7,8,9]] 
    for x in range(len(haystack)): 
     if needle in haystack[x]: 
      return x 
    raise Exception("needle: " + str(needle) + " not in haystack") 

有一个haystack.index(针)方法。 问题是:“有没有更好的方法来做到这一点?”

+0

我用的是指数在另一个类似的功能这个。 'if index1!= index2:haystack [index1] .extend(haystack.pop(index2))' – mbowden

回答

6

是的,没有必要范围内,对于初学者

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

如果你真的真的需要索引,使用enumerate

for x, hay in enumerate(haystack): 
    if needle in hay: 
    return x 
0

你可以做这样的事情有1班轮:

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

我认为应该工作(但它返回haystack元素)。如果针不在任何干草堆元素中,则会产生StopIteration

这听起来并不像你实际需要的指数,但如果这样做,使用enumerate(如提议由迪马的鲁德尼克优秀的答案):

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