简体   繁体   English

为什么用python中的map()函数列表理解可以返回None

[英]Why list comprehension with map() function in python can return None

>>> counters = [1,2,3,4]
>>> 
>>> [print(i, end=', ') for i in map(inc, counters)]

4, 5, 6, 7, [None, None, None, None]

Why does this code print [None, None, None, None] ? 为什么此代码打印[None, None, None, None]

Because print returns None ? 因为print返回None

So, the print is done ( 4, 5, 6, 7, ) and then the list comprehension is returned ( [None, None, None, None] ) 因此,打印完成( 4, 5, 6, 7, ),然后返回列表推导( [None, None, None, None]

What you want to do is use join: 你想要做的是使用join:

>>> ', '.join(str(i) for i in map(inc, counters))
'4, 5, 6, 7'

or use the sep argument of print (I don't have python3 right now but something like this:) 或者使用printsep参数 (我现在没有python3但这样的东西:)

print(*map(inc, counters), sep=', ')

print is a function but it return None that's why you are getting none print是一个函数,但它返回None ,这就是为什么你没有

Do this 做这个

In [3]: [i for i in map(abs, counters)]
Out[3]: [1, 2, 3, 4]

In [7]: a = print(1234)
1234

In [11]: print(a)
None

[print(i, end=', ') for i in map(inc, counters)]

so when you do this print prints i 1, 2, 3, 4, and then each time list comprehension return the output which is None hence None, None, None, None 因此,当执行此print打印i 1,2,3,4,然后每次list comprehension返回其输出是None因此无,无,无,无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM