0

最近我必须找到某物在哪个列表中。我使用了:

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(needle) 方法。问题是:“有没有更好的方法来做到这一点?”

4

2 回答 2

8

是的,对于初学者来说,不需要范围

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

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

for x, hay in enumerate(haystack):
  if needle in hay:
    return x
于 2012-12-17T12:14:04.777 回答
0

你可以用 1-liner 做这样的事情:

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

我认为应该可以(但它会返回 haystack 元素)。StopIteration如果针不在任何干草堆元素中,则会引发 a 。

听起来您实际上并不需要索引,但如果需要,请使用enumerate(如 Dima Rudnik 的出色回答所建议的那样):

def find_point(haystack,needle):
    return next(idx for idx,elem in enumerate(haystack) if needle in elem)
于 2012-12-17T12:31:06.427 回答