Home>

Available

N= 3
st= list (map (lambda s: ", K% d"% s, range (1, N))) #, K1, K2, K3

N is greater than 100.3 for brevity. How can all this be written without lamda or using format ?

  • Answer # 1

    Literally, usingformatinstead oflambdaand formatting via%:

    N= 3
    print (list (map (", K {}". format, range (1, N))))
    # Output: [', K1', ', K2']
    

    If a comma is needed to separate elements (no leading comma is needed), it is better to remove it from the format string, and usejointo assemble items into a string with a comma as a separator:

    print (",". join (map ("K {}". format, range (1, N))))
    # Conclusion: K1, K2
    

    Another variation on formatting with a percentage (we use the fact that", K% d"% sis equivalent to calling a method__mod__:", K% d" .__ mod __ (s))

    print (list (map (", K% d" .__ mod__, range (1, N))))
    

    But in general, now (with the presence of format and f-strings in Python, i.e. starting with Python 3.6), there is no particular sense in using percent for formatting at all. Yes, code using double underscore functions directly doesn't look very good.