每个语言,都有自己的特性,而一致性,是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))

 

相关文章:

  • 2022-02-22
  • 2021-07-02
  • 2021-12-13
  • 2022-03-01
  • 2022-02-16
  • 2022-12-23
  • 2021-06-24
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-06
  • 2021-11-03
相关资源
相似解决方案