python nonetype转换list,无法在Python中反转列表,从而获取“ Nonetype”作为清单

I have a .py file that takes a list, finds the lowest number, puts it into a new array, removes the lowest number from the first array, and repeats until the original array returns contains no more items:

def qSort(lsort):

listlength = len(lsort)

sortedlist = list()

if listlength == 0:

return lsort

else:

while listlength > 0:

lmin = min(lsort)

sortedlist.append(lmin)

lsort.remove(lmin)

listlength = len(lsort)

return sortedlist

Now another .py file imports the qSort and runs it on some list, saving it to a variable. Then I try to use the .reverse() command on the list and I end up getting it as a NoneType. I try to use reversed(), but all it does is say "":

from qSort import qSort #refer to my first Pastebin

qSort = qSort([5,42,66,1,24,5234,62])

print qSort #this prints the sorted list

print type(qSort) #this prints

print qSort.reverse() #this prints None

print reversed(qSort) #this prints ""

Can anyone explain why I can't seem to reverse the list, no matter what I do?

解决方案

As jcomeau mentions, the .reverse() function changes the list in place. It does not return the list, but rather leaves qSort altered.

If you want to 'return' the reversed list, so it can be used like you attempt in your example, you can do a slice with a direction of -1

So replace print qSort.reverse() with print qSort[::-1]

You should know slices, its useful stuff. I didn't really see a place in the tutorial where it was all described at once, (http://docs.python.org/tutorial/introduction.html#lists doesn't really cover everything) so hopefully here are some illustrative examples.

Syntax is: a[firstIndexInclusive:endIndexExclusive:Step]

>>> a = range(20)

>>> a

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> a[7:] #seventh term and forward

[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> a[:11] #everything before the 11th term

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a[::2] # even indexed terms. 0th, 2nd, etc

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> a[4:17]

[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

>>> a[4:17:2]

[4, 6, 8, 10, 12, 14, 16]

>>> a[::-1]

[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

>>> a[19:4:-5]

[19, 14, 9]

>>> a[1:4] = [100, 200, 300] #you can assign to slices too

>>> a

[0, 100, 200, 300, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值