Python loop for inside lambda

后端 未结 5 1189
夕颜
夕颜 2020-12-15 04:47

In my code I need to simplify as much as possible my line of code. EDIT: I think I\'m not clear enough - it needs to be one line of code. I need to put a for loop inside a l

相关标签:
5条回答
  • 2020-12-15 05:02

    Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

    x = lambda x: sys.stdout.write("\n".join(x) + "\n")
    
    0 讨论(0)
  • 2020-12-15 05:04

    Just in case, if someone is looking for a similar problem...

    Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code). Instead, you can use a simple list comprehension.

    [print(i) for i in x]
    

    BTW, the return values will be a list on None s.

    0 讨论(0)
  • 2020-12-15 05:09

    To add on to chepner's answer for Python 3.0 you can alternatively do:

    x = lambda x: list(map(print, x))
    

    Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.

    I'll just leave this here for reference.

    0 讨论(0)
  • 2020-12-15 05:14

    If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

    x = range(3)
    from __future__ import print_function           # if not python 3
    pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
    pra()
    pra('abc')
    
    0 讨论(0)
  • 2020-12-15 05:15

    anon and chepner's answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).

    However, you can get the print function very easily in python 2.x by importing from the standard library's future module. Check it out:

    >>>from __future__ import print_function
    >>>
    >>>iterable = ["a","b","c"]
    >>>map(print, iterable)
    a
    b
    c
    [None, None, None]
    >>>
    

    I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]'s output (you are interested in the side-effects only, I assume):

    >>>_ = map(print, iterable)
    a
    b
    c
    >>>
    
    0 讨论(0)
提交回复
热议问题