Why map(print, a_list) doesn't work?

后端 未结 6 1895
野趣味
野趣味 2020-12-18 19:55

For a normal function, map works well:

def increment(n):
    return n+1
l = [1, 2, 3, 4, 5]
l = map(increment, l)
print l
>>> [2, 3, 4,         


        
6条回答
  •  臣服心动
    2020-12-18 20:20

    The above answers work for Python 2, but not in Python 3 with the changes to both map and the print function.

    The solution I've arrived at to achieve what I wanted map(print, lst) to do in Python 3 is to unpack the list inside of the print call.

    lst = [1, 2, 3]
    print(*lst, sep='\n')
    

    Output:

    1
    2
    3
    

    You can find more detail around this in my answer to Use print inside lambda.

提交回复
热议问题