在python的嵌套列表中搜索 [英] searching within nested list in python

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

问题描述

我有一个列表:

l = [['en', 60, 'command'],['sq', 34, 'komand']]

我想搜索komandsq并返回l[1].

我可以为列表搜索定义自己的匹配功能吗?

Can I somehow define my own matching function for list searches?

推荐答案

类似的表达式:

next(subl for subl in l if 'sq' in subl)

会精确地为您提供您要搜索的子列表(如果没有这样的子列表,请提高StopIteration;如果后一种行为不是您想要的,请向next传递第二个参数[[例如,None,具体取决于您要返回的内容!]].因此,只需使用此结果值,或将其分配给您想要的任何名称,依此类推.

will give you exactly the sublist you're searching for (or raise StopIteration if there is no such sublist; if the latter behavior is not what you want, pass next a second argument [[e.g, [] or None, depending on what exactly you want!]] to return in that case). So, just use this result value, or assign it to whatever name you wish, and so forth.

当然,您可以轻松地将此表达式修饰为所需的任何功能,例如:

Of course, you can easily dress this expression up into any kind of function you like, e.g.:

def gimmethesublist(thelist, anitem, adef=None):
    return next((subl for subl in thelist if anitem in subl), adef)

但是,如果您要使用特定的变量或值,则通常最好使用内联代码对表达式进行编码.

but if you're working with specific variables or values, coding the expression in-line may often be preferable.

编辑:如果要搜索多个项目以查找包含任何一个(或更多)项目的子列表,

Edit: if you want to search for multiple items in order to find a sublist containing any one (or more) of your items,

its = set(['blah', 'bluh'])
next(subl for subl in l if its.intersection(subl))

,如果您要查找包含所有个项目的子列表,

and if you want to find a sublist containing all of your items,

next(subl for subl in l if its.issubset(subl))

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

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