Python map()函数遍历'无'元件

时间:2015-03-24 04:33:20

标签: python list nonetype map-function

我写了一个简单的map()函数,它迭代一个列表并打印列表中的'*'。我看到我的代码有一个小问题,我在输出中看到一个额外的'None'。有人可以帮我调试这个问题吗?

Problem Statement:
-----------------
Define a procedure histogram() that takes a list of integers and prints a
histogram to the screen. For example, histogram([4, 9, 7]) should print the
following:

****
*********
*******

源代码

def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    print histogram([4,7,5])


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出

****
*******
*****
None

4 个答案:

答案 0 :(得分:4)

在这一行:

print histogram([4,7,5])

您正在打印histogram函数的返回值,即None。您只需要调用该函数:

histogram([4,7,5])

答案 1 :(得分:1)

由于函数histogram没有返回任何内容。 print histogram([4,7,5])打印None

def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    histogram([4,7,5])


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出:

****
*******
*****

答案 2 :(得分:1)

替换

def main():
    # Test inputs
    print histogram([4,7,5])

def main():
    # Test inputs
    histogram([4,7,5])

注意:函数histogram没有任何return语句。

答案 3 :(得分:1)

写直方图([4,7,5])而不是打印直方图([4,7,5])


def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    histogram([4,7,5])

if __name__ == "__main__":
    import sys
    sys.exit(main())