2013-10-10 159 views
0

我已经得到了名单x是[10,20,30,40,50]
所以x的len为5
所以下面是有道理的:为什么这也会返回没有

>>> x=[10,20,30,40,50] 
>>> print(list(range(len(x)))) 
[0, 1, 2, 3, 4] 

我把上面为function,它似乎运行。
我在输出中获得的额外None是什么?

def foo(aList): 
    listLen = len(aList) 
    for x in list(range(listLen)): 
     print(x) 

x=[10,20,30,40,50] 
print(foo(x)) 

编辑
如果我申请上述扭转列表的任务似乎罚款,因此无不会引起一个问题:

def foo(aList): 
    newList = [] 
    listLen = len(aList) 
    for x in list(range(listLen)): 
     newList.append(aList[listLen-(x+1)]) 
    return newList 

x=[10,20,30,40,50] 
print(foo(x)) 
+2

为什么使用'print(foo(x))'如果函数已经打印了list的元素? – alexvassel

+0

作为一个方面说明,你不需要在'list'中包含'range'来迭代它。 – DzinX

回答

2

print发送数据到标准输出(通常是终端)。 print实际上并没有从函数中“返回”任何东西。要做到这一点,您需要return关键字。你的函数是print函数内部的结果并返回None(默认值)。函数外的print声明然后打印返回值为None

该修复程序可能是从您的功能返回列表,而不是打印它的元素。然后你可以在功能外打印它。沿着线的东西:

def foo(aList): 
    listLen = len(aList) 
    return list(range(listLen)) 

x=[10,20,30,40,50] 
print(foo(x)) 
2
print(foo(x)) 

这将打印您的Foo()函数的返回值。然而,foo()不会返回任何内容,这隐含地表示它的返回值是None。所以你最终打印“无”

也许你只是想这样的:

def foo(aList): 
    listLen = len(aList) 
    return list(range(listLen)): 

x=[10,20,30,40,50] 
print(foo(x)) 
2

您从富打印的返回值,并没有明确return语句的函数将返回无。

1
print(foo(x)) 

这将打印您的函数返回的内容。你的函数打印列表并且什么都不返回。

因此,正在打印的列表是您的函数打印的列表。打印功能打印无。

此功能应该做你想做的。

def foo(aList): 
    newList = [] 
    listLen = len(aList) 
    return range(listLen) 

然后

x=[10,20,30,40,50] 
print foo(x) 

你的函数将返回列表和打印语句将打印。


另一种方法可以不用打印就可以调用函数。

def foo(aList): 
    listLen = len(aList) 
    for x in list(range(listLen)): 
     print(x) 

x=[10,20,30,40,50] 
foo(x) 
+1

在这里,您只需返回您创建的列表中的第一个值 - 剩下的值就会消失在pythons垃圾回收器的void中。我怀疑这是OP想要的;-) – mgilson

+0

啊!垃圾收集器,邪恶的黑暗黑洞。我把一个重力中和器。列表值现在是安全的。 :d – shshank