简体   繁体   中英

object of type NoneType has no len

def medianeven (L):
    while len(L) > 2:
        L = L[1:(len(L)-1)]
    return average (L)

def medianodd (L):
    while len(L) > 1:
        L = L[1:(len(L)-1)]
    return L[0]

def median (L):
    new = L.sort()
    a = len(new)
    if a % 2 == 0:
        medianeven(new)
    else:
        medianodd(new)

It says TypeError: object of type 'NoneType' has no len() . Both medianeven and medianodd work, but median itself is not functioning.

.sort() is in-place and returns None .

Change this line:

new = L.sort()

To just this:

L.sort()

And replace all of your instances of new with just L . You also need to return the results of those function calls:

if a % 2 == 0:
    return medianeven(new)
else:
    return medianodd(new)

Also, Python's slices support negative indices, so this code:

L[1:(len(L)-1)]

Can be simplified to just

L[1:-1]

The sort() method call you have in the line:

new = L.sort();

doesn't return anything. Thus 'new' holds 'None', which has no length. I believe doing L.sort() will sort the list in place. Don't need to store it in 'new'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM