Python在列表列表中查找值 [英] Python finding a value in a list of lists

查看:96
本文介绍了Python在列表列表中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我不得不找到某物在哪个列表中.我曾经使用过:

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(len(haystack)):
        if needle in haystack[x]:
            return x
    raise Exception("needle: " + str(needle) + " not in haystack")

有一个haystack.index(needle)方法. 问题是:是否有更好的方法来做到这一点?"

There is a haystack.index(needle) method. The question is: "Is there a better way to do this?"

推荐答案

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

Yes, no need for range, for starters

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

如果您确实需要索引,请使用enumerate

And if you really really need the index, use enumerate

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

这篇关于Python在列表列表中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆