Python 为什么这也不返回
我得到了列表x,它是Python 为什么这也不返回,python,Python,我得到了列表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] 我已将上述内容放入一个函数,它似乎正在运行。 我在输出中得到的额外None是什么 def foo(aList): listLen = len(aList) for x in list(range(list
[10,20,30,40,50]
所以x的len是5。
因此,以下是有意义的:
>>> x=[10,20,30,40,50]
>>> print(list(range(len(x))))
[0, 1, 2, 3, 4]
我已将上述内容放入一个函数
,它似乎正在运行。我在输出中得到的额外
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))
print
将数据发送到标准输出(通常是终端)<代码>打印实际上不会从函数中“返回”任何内容。为此,您需要return
关键字。您的函数正在打印
函数内的结果,并返回无
(默认值)。函数外部的print
语句然后打印返回值None
修复方法可能是从函数返回列表,而不是打印它的元素。然后可以在函数外部打印它。大致如下:
def foo(aList):
listLen = len(aList)
return list(range(listLen))
x=[10,20,30,40,50]
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))
打印来自foo的返回值,没有显式return语句的函数将不返回任何值
print(foo(x))
这将打印函数返回的内容。函数打印列表,但不返回任何内容
因此,正在打印的列表就是函数打印的列表。print函数不打印任何内容
此函数应该执行您想要的操作
def foo(aList):
newList = []
listLen = len(aList)
return range(listLen)
然后
函数将返回列表,print语句将打印它
另一种方法是在不打印的情况下调用函数
def foo(aList):
listLen = len(aList)
for x in list(range(listLen)):
print(x)
x=[10,20,30,40,50]
foo(x)
如果函数已经打印了列表的元素,为什么要使用
print(foo(x))
呢?作为补充,您不需要在list
中包装range
来对其进行迭代。在这里,您只需返回您创建的列表中的第一个值,其余的值就会消失在pythons垃圾收集器的空隙中。我怀疑这是OP想要的;-)啊!垃圾收集器,邪恶的黑暗黑洞。我放了一个重力中和器。列表值现在是安全的:D
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)