searching within nested list in python

前端 未结 4 721
鱼传尺愫
鱼传尺愫 2021-01-13 18:56

I have a list:

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

I want to search for komand or sq and get

4条回答
  •  滥情空心
    2021-01-13 19:09

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

提交回复
热议问题