Python 内置函数 Python builtins 模块

 Python常用的内置函数


下面列举一些常用的Python内置函数


点击跳转到指定函数


abs()divmod()input()open()enumerate()
int()ord()str()eval()isinstance()
pow()sum()issubclass()print()sorted()
bin()oct()iter()tuple()next()
bool()filter()len()range()type()
float()list()hex()callable()set()
min()id()chr()dir()help()
vars()dict()map()zip()max()

abs()函数

描述

abs() 函数返回数字的绝对值。

语法

abs(n)
参数:n 数值表达式
返回值:返回n的绝对值

示例

print(abs(1 + 2j))  # 2.23606797749979
print(abs(-100))  # 100

Tips

如果参数为一个复数,则返回复数的模。如一个复数为 a + bj,则返回值为 a、b 的平方和再开根号,即 math.sqrt(a**2 + b**2)

divmod()函数

描述

取两个(非复数)数字作为参数,并在使用整数除法时返回由商和余数组成的一对数字。对于混合的操作数类型,应用二元算术运算符的规则。对于整数,结果与(x // y, x % y)相同。对于浮点数,结果为(q, a % b),其中q通常为math.floor(a / b),也有可能比这个结果小1。

语法

divmod(x, y)
参数:x, y 数值
返回值:返回一个元组(x // y, x % y)

示例

print(divmod(3, 2))  # (1, 1)
print(divmod(5, 3))  # (1, 2)

input()函数

描述

如果有prompt参数,则将它输出到标准输出且不带换行。该函数然后从标准输入读取一行,将它转换成一个字符串(去掉一个末尾的换行符),然后返回它,返回值为 str 类型。当读取到EOF时,会产生EOFError。

语法

input(prompt='')
参数:可选,字符串
返回值:返回控制台的输入,类型为str

open()函数

描述

用于打开一个文件,创建一个 file 对象。如果文件不能被打开, 抛出 OSError 异常.

语法

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
参数:
file: 必需,文件路径(相对或者绝对路径)。
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 可选字符串,指定如何处理编码和解码错误 - 这不能在二进制模式下使用。
newline: 区分换行符(仅适用于文本模式)
closefd: 传入的file参数类型
返回值:返回文件对象

更多内容请参考菜鸟教程:https://www.runoob.com/python/file-methods.html

enumerate()函数

描述

用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标(默认从0开始),一般用在 for 循环当中。

语法

enumerate(iterable, start=0)
参数:
iterable:可迭代的对象
start:序列下标开始位置
返回值:返回元素索引,元素值

示例

for index, value in enumerate(['a', 'b', 'c']):
    print(index, value)
# 输出:
# 0 a
# 1 b
# 2 c

int()函数

描述

用于将一个字符串或数字转换为整型,如果没有给出参数,则返回0。如果参数为浮点数,则返回整数部分。

语法

int(x, base=10)
参数:
x:字符串或数字
base:基数,允许的值为02-36
返回值:返回整型数字

示例

print(int("128"))  # 128
print(int(3.14))  # 3

ord()函数

描述

ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

语法

ord(c)
参数:
c:一个字符
返回值:返回对应的十进制整数

示例

print(ord('A'))  # 65
print(ord('中'))  # 20013

str()函数

描述

str函数将对象转换为字符串,返回对象的string版本。如果未提供对象,则返回空字符串。否则,str()的行为取决于是否给出编码或错误

语法

str(object='', encoding=None, errors='strict')
参数:
object:目标对象
encoding;默认为sys.getdefaultencoding()
errors:默认为strict
返回值:返回字符串

示例

string = str([1, 2, 3])
print(string)
print(type(string))
# 输出:
# [1, 2, 3]
# <class 'str'>

eval()函数

描述

eval() 函数用来执行一个字符串表达式,并返回表达式的值。

语法

eval(expression, globals=None, locals=None) 
参数:
expression -- 表达式。
globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
返回值:返回表达式计算的结果

示例

print(eval('1+2+3'))  # 6
eval('print("hello world")')  # hello world

Tips

该函数很强大,但须慎用
exec()函数支持语句的动态执行。globals()和locals()函数分别返回当前的全局和局部字典,可以用于传递给eval或exec()。

isinstance()函数

描述

isinstance() 函数来判断一个对象是否是一个已知的类型
如果object是clsaainfo的一个实例(或者是classinfo的直接、间接或虚拟子类的实例),那么则返回true。如果对象不是给定类型的对象,则函数始终返回false。

语法

isinstance(object, classinfo)
参数:
object:一个对象
classinfo:可以是直接或间接类名、基本类型或者由他们组成的元组。
返回值:返回布尔值

示例

print(isinstance(1, int))  # True
print(isinstance('hi', (int, str)))  # True

pow()函数

描述

返回a的b次方

语法

pow(a, b[, c])
参数:
a,b,c:数值
返回值:返回a的b次方,如果c存在则计算x 的y次方再除以z,(计算效率比pow(x, y) % z更高)

示例

print(pow(2, 3))  # 8

sum()函数

描述

sum() 方法对系列进行求和计算。

语法

sum(iterable[, start])
参数:
iterable:可迭代的对象
start: 起始位置,不允许是一个字符串
返回值:返回对象所有元素之和

示例

print(sum([1, 2, 3]))  # 6
print(sum([1, 2, 3], 1))  # 7 即 6 + 1 = 7

issubclass()函数

描述

issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类(直接、 间接或 虚拟) 。

语法

issubclass(class, classinfo)
参数:
class:类
classinfo:类
返回值:返回

示例

class A:
    pass
class B(A):
    pass
    
print(issubclass(B,A))    # True

print()函数

描述

print() 方法用于打印输出。sep, end 和 file,如果提供这三个参数的话,必须以关键参数的形式。

语法

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
参数:
objects:表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
sep:用来间隔多个对象,默认值是一个空格。
end:用来设定以什么结尾。
file:要写入的文件对象。
flush:输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。
返回值:返回None

示例

print('hello world')  # hello world

bin()函数

描述

bin() 返回一个整数 int 或者长整数 long int 的二进制表示。

语法

bin(x)
参数:
x:一个整数
返回值:返回整数对应的二进制数

示例

print(bin(100))  # 0b1100100

iter()函数

描述

iter() 函数用来生成迭代器。

语法

iter(object[, sentinel])
参数:
object -- 支持迭代的集合对象。
sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。
返回值:返回一个迭代器

示例

list1 = ['a', 'b', 'c']
for i in iter(list1):
    print(i)
# 输出;
# a
# b
# c

tuple()函数

描述

将可迭代的对象转换为元组

语法

tuple( iterable )
参数:
iterable:可迭代的对象
返回值:返回一个元组

示例

print(tuple('abcdefg'))  # ('a', 'b', 'c', 'd', 'e', 'f', 'g')

bool()函数

描述

将对象转换为布尔类型的值

语法

bool(x)
参数:
x:一个对象
返回值:返回其布尔值

示例

print(bool(123))  # True
print(bool(0))  # False
print(bool(None))  # False

filter()函数

描述

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

语法

filter(function, iterable)
参数:
function:一个函数
iterable:可迭代的对象
返回值: Pyhton2.7 返回列表,Python3.x 返回迭代器对象

示例

# 判断是否为整数
def is_num(x):
    return isinstance(x, int)


filter1 = filter(is_num, [1, '2', 'a', '4', 5, 6])
print(filter1)  # <filter object at 0x0000015DF87F66A0>
print(next(filter1))  # 1

len()函数

描述

返回对象长度

语法

len(object)
参数:
object:对象
返回值:返回对象长度

示例

print(len('python'))  # 6
print(len([1, 2, 3]))  # 3

range()函数

描述

range() 函数可创建一个整数列表,一般用在 for 循环中。

语法

rangerange(start, stop[, step])
参数:
start:开始,默认从0开始
stop:结束,输出的值不包括stop
step:步长
返回值:

示例

for i in range(5):
    print(i)
# 0
# 1
# 2
# 3
# 4
for i in range(1, 5):
    print(i)
# 1
# 2
# 3
# 4
for i in range(1, 5, 2):
    print(i)

# 1
# 3

type()函数

描述

type() 函数如果只有第一个参数则返回对象的类型,三个参数返回新的类型对象。

语法

type(object)
type(name, bases, dict)
参数:
object:对象
name:类名
bases:基类的元组
dict:字典,类内定义的命名空间变量
返回值:一个参数返回对象类型, 三个参数,返回新的类型对象。

示例

print(type(120))  # <class 'int'>
print(type([]))  # <class 'list'>

float()函数

描述

用于将整数和字符串转换成浮点数。

语法

float(x)
参数:x:整数或字符串
返回值:返回浮点数

示例

print(float(123))  # 123.0
print(float('64.9'))  # 64.9

list()函数

描述

将一个对象转换为列表

语法

list(seq=())
参数:
seq:序列
返回值:列表

示例

print(list('12345'))  # ['1', '2', '3', '4', '5']
print(list((1, 2, 3)))  # [1, 2, 3]
print(list({'a': 1, 'b': 2}))  # ['a', 'b']

callable()函数

描述

用于检查一个对象是否是可调用的

语法

callable(object)
参数:
object:对象
返回值:返回布尔值

示例

def say_sth(string):
    print(string)


print(callable(say_sth))  # True

chr()函数

描述

根据给定整数返回对应Unicode字符

语法

chr(code)
参数:
code:整数,范围为0 <= code <= 0x10ffff(65536)
返回值:返回对应字符

示例

print(chr(10000))  # ✐
print(chr(20000))  # 丠

vars()函数

描述

vars() 函数返回对象object的属性和属性值的字典对象。

语法

vars(object=None)
参数:
object:一个对象
返回值:返回对象属性与属性值组成的字典

示例

print(vars())  # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002F54EB408E0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/python_project/BasicCalculate01/py_dir/test01.py', '__cached__': None, 'sys': <module 'sys' (built-in)>}

map()函数

描述

map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

语法

map(function, iterable, ...)
参数:
function:函数
iterable:可迭代的
返回值:
Python 2.x 返回列表。
Python 3.x 返回迭代器。

示例

iter1 = map(lambda x: x * 2, [1, 2, 3])  # 对序列每个元素乘以2
print(iter1)  # <map object at 0x000002E77FF8A670>
print(next(iter1))  # 2

# 对两个序列相同位置的元素相乘
def square(x, y):
    return x * y


iter1 = map(square, [1, 2, 3], [4, 5, 6])
print(next(iter1))  # 4

max()函数

描述

返回一个序列的最大值

语法

max(iterable)
参数:
iterable:可迭代的对象
返回值:返回对象元素的最大值

示例

print(max([1, 2, 3, 100]))   # 100
# 对于非数字的序列,比较其Unicode码大小
print(max(['a', 'b', 'c', '一', '二', '三']))   # 二

zip()函数

描述

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

语法

zip([iterable, ...])
参数:
iterable:可迭代的对象
返回值:
python2 返回列表
python3 返回迭代器

示例

a = [1, 2, 3]
b = [4, 5, 6]
zip1 = zip(a, b)
print(zip1)  # <zip object at 0x00000117C7C9AB80>
print(next(zip1))  # (1, 4)

min()函数

描述

返回序列最小值,可参照 max 函数

set()函数

描述

set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

语法

set([iterable])
参数:
iterable:可迭代的对象
返回值:返回集合

示例

print(set([1, 2, 3, 2, 1]))  # {1, 2, 3}  将重复的值去除,集合元素无顺序

help()函数

描述

help() 函数用于查看函数或模块用途的详细说明。

语法

help([object])
参数:
object:对象
返回值:返回帮助信息

示例

help(int)
# Help on class int in module builtins:
# 
# class int(object)
#  |  int([x]) -> integer
#  |  int(x, base=10) -> integer
#  |  
#  |  Convert a number or string to an integer, or return 0 if no arguments
#  |  are given.  If x is a number, return x.__int__().  For floating point
#  |  numbers, this truncates towards zero.
#  |  
#  |  If x is not a number or if base is given, then x must be a string,
#  |  bytes, or bytearray instance representing an integer literal in the
#  |  given base.  The literal can be preceded by '+' or '-' and be surrounded
#  |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
#  |  Base 0 means to interpret the base from the string as an integer literal.
#  |  >>> int('0b100', base=0)
#  |  4
#  |  
#  |  Built-in subclasses:
#  |      bool
#  |  
#  |  Methods defined here:
#  |  
#  |  __abs__(self, /)
#  |      abs(self)
#  |  
#  |  __add__(self, value, /)
#  |      Return self+value.
#  |  
#  |  __and__(self, value, /)
#  |      Return self&value.
#  |  
#  |  __bool__(self, /)
#  |      self != 0
#  |  
#  |  __ceil__(...)
#  |      Ceiling of an Integral returns itself.
#  |  
#  |  __divmod__(self, value, /)
#  |      Return divmod(self, value).
#  |  
#  |  __eq__(self, value, /)
#  |      Return self==value.
#  |  
#  |  __float__(self, /)
#  |      float(self)
#  |  
#  |  __floor__(...)
#  |      Flooring an Integral returns itself.
#  |  
#  |  __floordiv__(self, value, /)
#  |      Return self//value.
#  |  
#  |  __format__(self, format_spec, /)
#  |      Default object formatter.
#  |  
#  |  __ge__(self, value, /)
#  |      Return self>=value.
#  |  
#  |  __getattribute__(self, name, /)
#  |      Return getattr(self, name).
#  |  
#  |  __getnewargs__(self, /)
#  |  
#  |  __gt__(self, value, /)
#  |      Return self>value.
#  |  
#  |  __hash__(self, /)
#  |      Return hash(self).
#  |  
#  |  __index__(self, /)
#  |      Return self converted to an integer, if self is suitable for use as an index into a list.
#  |  
#  |  __int__(self, /)
#  |      int(self)
#  |  
#  |  __invert__(self, /)
#  |      ~self
#  |  
#  |  __le__(self, value, /)
#  |      Return self<=value.
#  |  
#  |  __lshift__(self, value, /)
#  |      Return self<<value.
#  |  
#  |  __lt__(self, value, /)
#  |      Return self<value.
#  |  
#  |  __mod__(self, value, /)
#  |      Return self%value.
#  |  
#  |  __mul__(self, value, /)
#  |      Return self*value.
#  |  
#  |  __ne__(self, value, /)
#  |      Return self!=value.
#  |  
#  |  __neg__(self, /)
#  |      -self
#  |  
#  |  __or__(self, value, /)
#  |      Return self|value.
#  |  
#  |  __pos__(self, /)
#  |      +self
#  |  
#  |  __pow__(self, value, mod=None, /)
#  |      Return pow(self, value, mod).
#  |  
#  |  __radd__(self, value, /)
#  |      Return value+self.
#  |  
#  |  __rand__(self, value, /)
#  |      Return value&self.
#  |  
#  |  __rdivmod__(self, value, /)
#  |      Return divmod(value, self).
#  |  
#  |  __repr__(self, /)
#  |      Return repr(self).
#  |  
#  |  __rfloordiv__(self, value, /)
#  |      Return value//self.
#  |  
#  |  __rlshift__(self, value, /)
#  |      Return value<<self.
#  |  
#  |  __rmod__(self, value, /)
#  |      Return value%self.
#  |  
#  |  __rmul__(self, value, /)
#  |      Return value*self.
#  |  
#  |  __ror__(self, value, /)
#  |      Return value|self.
#  |  
#  |  __round__(...)
#  |      Rounding an Integral returns itself.
#  |      Rounding with an ndigits argument also returns an integer.
#  |  
#  |  __rpow__(self, value, mod=None, /)
#  |      Return pow(value, self, mod).
#  |  
#  |  __rrshift__(self, value, /)
#  |      Return value>>self.
#  |  
#  |  __rshift__(self, value, /)
#  |      Return self>>value.
#  |  
#  |  __rsub__(self, value, /)
#  |      Return value-self.
#  |  
#  |  __rtruediv__(self, value, /)
#  |      Return value/self.
#  |  
#  |  __rxor__(self, value, /)
#  |      Return value^self.
#  |  
#  |  __sizeof__(self, /)
#  |      Returns size in memory, in bytes.
#  |  
#  |  __sub__(self, value, /)
#  |      Return self-value.
#  |  
#  |  __truediv__(self, value, /)
#  |      Return self/value.
#  |  
#  |  __trunc__(...)
#  |      Truncating an Integral returns itself.
#  |  
#  |  __xor__(self, value, /)
#  |      Return self^value.
#  |  
#  |  as_integer_ratio(self, /)
#  |      Return integer ratio.
#  |      
#  |      Return a pair of integers, whose ratio is exactly equal to the original int
#  |      and with a positive denominator.
#  |      
#  |      >>> (10).as_integer_ratio()
#  |      (10, 1)
#  |      >>> (-10).as_integer_ratio()
#  |      (-10, 1)
#  |      >>> (0).as_integer_ratio()
#  |      (0, 1)
#  |  
#  |  bit_length(self, /)
#  |      Number of bits necessary to represent self in binary.
#  |      
#  |      >>> bin(37)
#  |      '0b100101'
#  |      >>> (37).bit_length()
#  |      6
#  |  
#  |  conjugate(...)
#  |      Returns self, the complex conjugate of any int.
#  |  
#  |  to_bytes(self, /, length, byteorder, *, signed=False)
#  |      Return an array of bytes representing an integer.
#  |      
#  |      length
#  |        Length of bytes object to use.  An OverflowError is raised if the
#  |        integer is not representable with the given number of bytes.
#  |      byteorder
#  |        The byte order used to represent the integer.  If byteorder is 'big',
#  |        the most significant byte is at the beginning of the byte array.  If
#  |        byteorder is 'little', the most significant byte is at the end of the
#  |        byte array.  To request the native byte order of the host system, use
#  |        `sys.byteorder' as the byte order value.
#  |      signed
#  |        Determines whether two's complement is used to represent the integer.
#  |        If signed is False and a negative integer is given, an OverflowError
#  |        is raised.
#  |  
#  |  ----------------------------------------------------------------------
#  |  Class methods defined here:
#  |  
#  |  from_bytes(bytes, byteorder, *, signed=False) from builtins.type
#  |      Return the integer represented by the given array of bytes.
#  |      
#  |      bytes
#  |        Holds the array of bytes to convert.  The argument must either
#  |        support the buffer protocol or be an iterable object producing bytes.
#  |        Bytes and bytearray are examples of built-in objects that support the
#  |        buffer protocol.
#  |      byteorder
#  |        The byte order used to represent the integer.  If byteorder is 'big',
#  |        the most significant byte is at the beginning of the byte array.  If
#  |        byteorder is 'little', the most significant byte is at the end of the
#  |        byte array.  To request the native byte order of the host system, use
#  |        `sys.byteorder' as the byte order value.
#  |      signed
#  |        Indicates whether two's complement is used to represent the integer.
#  |  
#  |  ----------------------------------------------------------------------
#  |  Static methods defined here:
#  |  
#  |  __new__(*args, **kwargs) from builtins.type
#  |      Create and return a new object.  See help(type) for accurate signature.
#  |  
#  |  ----------------------------------------------------------------------
#  |  Data descriptors defined here:
#  |  
#  |  denominator
#  |      the denominator of a rational number in lowest terms
#  |  
#  |  imag
#  |      the imaginary part of a complex number
#  |  
#  |  numerator
#  |      the numerator of a rational number in lowest terms
#  |  
#  |  real
#  |      the real part of a complex number
# 

next()函数

描述

next() 返回迭代器的下一个项目。

next() 函数要和生成迭代器的iter() 函数一起使用。

语法

next(iterator[, default])
参数:
iterator -- 可迭代对象
default -- 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发 StopIteration 异常。
返回值:返回

示例

demo = iter([1, 2, 3])
print(next(demo))  # 1
print(next(demo))  # 2
print(next(demo))  # 3

dict()函数

描述

将对象转换为字典

语法

dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)
参数:
**kwargs -- 关键字
mapping -- 元素的容器。
iterable -- 可迭代对象。
返回值:返回字典

示例

demo = [(1, 'a'), (2, 'b'), (3, 'c')]
print(dict(demo))  # {1: 'a', 2: 'b', 3: 'c'}

hex()函数

描述

hex() 函数用于将10进制整数转换成16进制,以字符串形式表示。

语法

hex(x)
参数:
x:整数
返回值:返回十六进制数,以字符串形式表示

示例

print(hex(100))  # 0x64
print(type(hex(1000)))  # <class 'str'>

dir()函数

描述

dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

语法

dir([object])
参数:
object:对象
返回值:返回对象属性列表

示例

print(dir(int))  # ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

id()函数

描述

id() 函数返回对象的唯一标识符,标识符是一个整数。

CPython 中 id() 函数用于获取对象的内存地址。

语法

id([object])
参数:
object:对象
返回值:返回对象内存地址

示例

print(id(0))  # 140706455340672

oct()函数

描述

oct() 函数将一个整数转换成8进制字符串。

语法

oct(x)
参数:
x:整数
返回值:返回八进制数,类型为字符串

示例

print(oct(10))  # 0o12
print(type(oct(10)))  # <class 'str'>

sorted()函数

描述

sorted() 函数对可迭代的对象进行排序。

语法

sorted(iterable, cmp=None, key=None, reverse=False)  # Python2
sorted(iterable, key=None, reverse=False)  # Python3
参数:
iterable:可迭代的对象
cmp:用于比较的函数
key:用来进行比较的元素
reverse:反转排序后的序列
返回值:返回重新排序的列表。

示例

print(sorted([10, 24, -180, 75]))  # [-180, 10, 24, 75]
print(sorted([10, 24, -180, 75], reverse=True))  # [75, 24, 10, -180]

欢迎转载!如转载请附上本文地址

若您在上文发现了错误,请在评论区处反馈,谢谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值