最近我必须找到某个列表中的某些内容。我使用了:
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) 方法。
问题是:“有更好的方法吗?”
是的,对于初学者来说不需要范围
for hay in haystack:
if needle in hay:
return hay
如果您确实需要索引,请使用enumerate
for x, hay in enumerate(haystack):
if needle in hay:
return x
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)