python的一致性,1sorted和len

  每个语言,都有自己的特性,而一致性,是python语言特性重要的一个环节。

  比如排序,我们不是aaa.sort(),而是 sorted(aaa),比如len,不是aaa.length(),而是len(aaa)

今天介绍一下sorted的一个特性:

def takeSecond(elem):

    if (len(elem)>3):
        return elem[3]
    else:
        return elem[0]

# random list
random = ['wcf1','wcf2','wcf3','wcf3','wcf2','wcf9','wc','10w']

# sort list with key
sortedList = sorted(random, key=takeSecond)

# print list
print('Sorted list:', sortedList)

这是通过指定key,来指定排序依据。

再比如:

import random

class myfriend:
    def __len__(self):
        i = random.randint(3, 6)
        return i

mycls=myfriend()
print(len(mycls))
print(len(mycls))
print(len(mycls))
print(len(mycls))
print(len(mycls))
print(len(mycls))