Search code examples
pythonlambdaxlsxcycle

Explain python cycle with lambdas, please


i need to edit code for my needs, but unluckily i don't have a choice to rewrite from zero, so i must understand what is this, because deadline is in 11 hours. halp a junior find his job

    if text and segment:
        if "Office" in segment:
            if True in list(map(lambda x: x in text, _classes[_classB][0])):
                return "Класс Б"
        if "Warehouse" in segment:
            if True in list(map(lambda x: x in text, _classes[_classB][0])) or \
                    True in list(map(lambda x: x in text and True in [w not in text for w in _classes[_classA][0]], 
                        _classes[_classB][1])):

                return "Class B"    
        return ""
    return ""

may you eplain what the hell is

 True in list(map(lambda x: x in text and True in [w not in text for w in _classes[_classA][0]],_classes[_classB][1])):

or something like "unlambda"? big thanks

UPD: i need to add a rule: "if landsize is >9000 then ..." where landsize in another column"


Solution

  •  True in list(map(lambda x: x in text and True in [w not in text for w in _classes[_classA][0]],_classes[_classB][1])):
    

    This is an absolute nightmare of code, so let's break it down.

    True in list(map(...))
    

    The map() function will return a map of objects based on some conversion function and an input. list() will convert it into a list.

    lambda x: x in text and True in [w not in text for w in _classes[_classA][0]],_classes[_classB][1]
    

    We can take the lambda out and turn it into a function:

    # globals variables to make our lives easier. Bad practice but obviously they don't
    # care about that.
    text = ...
    _classes = ...
    
    def mylambda(x):
      """
      Checks that x exists in text and some class doesn't appear in text.
      """
      classA0 = _classes[_classA][0]
      classInText= w not in text for w in classA0
      return x in text and True in classInText
    

    Now, we can simplify it down:

    list(map(mylambda, _classes[_classB][1])):
    

    This statement will return a list of booleans.

    True in list(map(mylambda, _classes[_classB][1])):
    

    If, for any value in _classes[_classB][1], that value exists in text and some value in _classes[_classA][0] doesn't exist in text, this will return True.

    Now that that's over, please burn this code and never speak of it again.