简体   繁体   English

在python中的嵌套列表中搜索

[英]searching within nested list in python

I have a list: 我有一个清单:

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

I want to search for komand or sq and get l[1] returned. 我想搜索komandsq并返回l[1]

Can I somehow define my own matching function for list searches? 我能以某种方式为列表搜索定义自己的匹配函数吗?

An expression like: 一个表达式:

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

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 [[eg, [] or None , depending on what exactly you want!]] to return in that case). 会给你准确的你正在搜索的子列表(或者如果没有这样的子列表则提高StopIteration ;如果后者的行为不是你想要的,则next传递第二个参数[[eg, []None ,具体取决于究竟是什么你想要!]]在这种情况下返回)。 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, eg: 当然,您可以轻松地将此表达式添加到您喜欢的任何类型的功能中,例如:

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))

You can do it this way: 你可以这样做:

def find(value, seq):
    for index, item in enumerate(seq):
        if value in item: 
            return index, item

In [10]: find('sq', [['en', 60, 'command'],['sq', 34, 'komand']])
Out[10]: (1, ['sq', 34, 'komand'])

Or if you want a general solution: 或者,如果您想要一般解决方案:

def find(fun, seq):
    for index, item in enumerate(seq):
        if fun(item): 
            return index, item

def contain(value):
    return lambda l: value in l

In [14]: find(contain('komand'), [['en', 60, 'command'],['sq', 34, 'komand']])
Out[14]: (1, ['sq', 34, 'komand'])

If all you're trying to do is return the first list that contains a match for any of the values then this will work. 如果您要做的只是返回包含任何值匹配的第一个列表,那么这将起作用。

def search(inlist, matches):
    for li in inlist:
        for m in matches:
            if m in li:
                return li
    return None

>>> l = [['en', 60, 'command'],['sq', 34, 'komand']]
>>> search(l, ('sq', 'komand'))
['sq', 34, 'komand']

Yes: 是:

has_oneof = lambda *patterns: lambda: values any(p in values for p in patterns)
result = itertools.ifilter(has_oneof('komand', 'sq'), l).next()
print result # prints ['sq', 34, 'komand']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM