searching within nested list in python

前端 未结 4 677
鱼传尺愫
鱼传尺愫 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:20

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

提交回复
热议问题