Python 内置函数 - zhongjiajie/zhongjiajie.github.com GitHub Wiki

python-内置方法

assert

断言方法,它有助于在程序的早期发现问题,而不是等到程序后期才发现条件不符合assert is a statement and not a function even in python3,所以不能使用assert(condition),使用的标准是assert <condition>, "assertion failed output"

# telling the program to test that condition, and immediately trigger an error if the condition is false
assert condition
# equivalent
if not condition:
    raise AssertionError()

sorted

对序列进行排序,可指定排序的key及是否倒序

sorted(iterable, /, *, key=None, reverse=False)
   Return a new list containing all items from the iterable in ascending order.
   A custom key function can be supplied to customize the sort order, and the
   reverse flag can be set to request the result in descending order.

其中还可以根据自定义的函数进行排序,写一个自定义函数,然后sorted(iter, key=UDF)的方式实现排序

reversed

调转序列顺序

class reversed(object)
  reversed(sequence) -> reverse iterator over values of the sequence
  Return a reverse iterator

bisect

排序是一个高额的消耗,所以对已排序序列管理显得非常重要

  • bisect.bisect(seq, needle): 查看needle中对应有序序列list的index,然后通过seq.insert(index, needle)完成插入
  • bisect.insort(seq, needle): 将needle直接插入有序序列list中,完成了bisect.bisect(seq, needle); seq.insert(index, needle)中的操作

bisect 可以用来建立一个用数字作为索引的查询表格,比如说把分数和成绩

def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    i = bisect.bisect(breakpoints, score)
    return grades[i]

ord

chr是想相对应操作,ord获取的是一个字符串或者unicode所代表的整数,如ord('a')=97ord('€')=8364

isinstance

  • isinstance(obj, list): 判断obj是不是list实例
  • isinstance(obj, (list,tuple)): 判断obj是不是list实例或者tuple实例
⚠️ **GitHub.com Fallback** ⚠️