Why do you want Lambda fumes?



  • Study PythonI ran into you. lambda- Functions. But I haven't found an example yet. Really. Elementary examples of species are needed. print(lambda x, y: x**2 + y**2)where it's possible to remove the functional screwdriver. What are they really useful for?


  • QA Engineer

    They can't be 100%. I need you.I mean, without depositing operations, you can't write a program without a lambda fuque, but it's shorter and more comfortable. For example, a dictionary should be printed in order to reduce each value:

    bigrams = {"AB": [10, 11, 12], "BC": [5, -5, 8], "CD": [105, 1, 0], 
               "DE": [6, 6], "EF": [15, 20, 15], "FG": [22, 11, 32], 
               "GH": [20, 20, 20]}
    sorter = sorted(bigrams, key=lambda key: sum(bigrams[key]), reverse=True)
    

    for key in sorter:
    print(key, bigrams[key])

    Otherwise, you have to write a function:

    from functools import partial

    def sort_func(key, dict):
    return sum(dict[key])

    bigrams = {"AB": [10, 11, 12], "BC": [5, -5, 8], "CD": [105, 1, 0],
    "DE": [6, 6], "EF": [15, 20, 15], "FG": [22, 11, 32],
    "GH": [20, 20, 20]}
    partial_sort = partial(sort_func, dict=bigrams)
    sorter = sorted(bigrams.keys(), key=partial_sort, reverse=True)

    for key in sorter:
    print(key, bigrams[key])

    The result is the same, but with the lambda shorter, you don't have to look for your eyes. sort_func - It's clear how the collection is sorted. The standard library is equipped with other functions: mapreducefiltersortedanyall

    You can write a lock:

    def addition(x):
    return lambda y: x + y
    add_to_ten = addition(10)
    print(add_to_ten(8))
    print(add_to_ten(6))

    In the idea, the Lambada function is exactly the same as normal functions, but without the name:

    def func(x):
    func = lambda x: x + 1
    return 100

    import dis
    print(dis.dis(func))

    It shows that a new function is actually being created without deception.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2