附加到列表中的Python程序返回None Type数组 [英] Python program returning None Type array when append to the list
问题描述
我的python程序有一个小问题。情况是我试图在数组中使用 myarray.append()
,但是在python shell中,当我在python shell:
My python program has a minor problem. The case is that I'm trying to use myarray.append()
to my array, but in the python shell, it's telling me this when I do a test appending in the python shell:
>> l.append('1') # l is already defined
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
l.append('1')
AttributeError: 'NoneType' object has no attribute 'append'
>>
我对这个问题很困惑,但是无论如何,我会让你看一下代码:
I'm very confused about this problem, but anyways, I'll let you see the code:
l=[] #*
i=1
while True:
if 3*i<1000:
l.append(str(i)) #*
else:
break
i+=1
l=l.sort()
print l
*我相信这是造成问题的主要因素
我可能只是发疯而没有意识到,但是如果可以的话,请这样做。
I might just be going crazy and not realizing, but if you can help, please do.
PS当我运行程序时,在 print l
上,它只是输出 None
P.S. When I run the program, on print l
, it just output's None
推荐答案
问题出在
l = l.sort()
sort()方法对列表进行原位排序;列表本身已重新排序,而不是返回新列表。该方法返回无,然后将其分配给 l
。因此,您只需要删除任务即可。
The sort() method sorts a list in-place; the list itself is reordered, rather than returning a new list. The method returns None, which you are then assigning to l
. So you just need to remove the assignment.
另一种方法是使用
l = sorted(l)
实际上将复制原始列表,并带有元素按排序顺序。
which will actually make a copy of the original list with the elements in sorted order.
这篇关于附加到列表中的Python程序返回None Type数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!