Is it possible to have multiple statements in a python lambda expression?

后端 未结 18 1971
感情败类
感情败类 2020-12-12 21:33

I am a python newbie trying to achieve the following:

I have a list of lists:

lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]

18条回答
  •  星月不相逢
    2020-12-12 22:09

    You can do it in O(n) time using min and index instead of using sort or heapq.

    First create new list of everything except the min value of the original list:

    new_list = lst[:lst.index(min(lst))] + lst[lst.index(min(lst))+1:]
    

    Then take the min value of the new list:

    second_smallest = min(new_list)
    

    Now all together in a single lambda:

    map(lambda x: min(x[:x.index(min(x))] + x[x.index(min(x))+1:]), lst)
    

    Yes it is really ugly, but it should be algorithmically cheap. Also since some folks in this thread want to see list comprehensions:

    [min(x[:x.index(min(x))] + x[x.index(min(x))+1:]) for x in lst]
    

提交回复
热议问题