Built-in Functions

(一)常见函数

(1)abs(x):

求绝对值。参数可以是int或float类型。

(2)min()

函数功能为求传入的多个参数中的最小值,或者传入的可迭代对象元素中的最小值。还可以传入命名参数key,其为一个函数,用来指定取最小值的方法。default命名参数用来指定最小值不存在时返回的默认值。

形式:
  • min(iterable, *[, key, default])
  • min(arg1, arg2, *args[, key])

1.当函数只有一个位置参数时,该参数必须是可迭代类型,否则会报TypeError错误。返回该可迭代对象中的最小值:

>>> min('1234')
'1'
>>> min(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> min([2, 5, -9])
-9

2.当函数有多个位置参数时,这些位置参数的类型必须一致。返回最小的一项:

>>> min([2, 5, -9])
-9
>>> min([2, 5, -9], 8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'list'
>>> min([2, 5, -9], (3, 8))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'tuple' and 'list'
>>> min(1, 6, 9)
1
>>> min([1, 6], [3, 5])
[1, 6]

3.可选的关键字参数key是一个只有一个参数的函数,指定对参数进行的操作。min()再对操作的结果求它们的最小值:

>>> def f():
...     return abs(int(a))
...
>>> def f(a):
...     return abs(int(a))
...
>>> min(1, '-3', '6', key=f)
1
>>> f = lambda x: int(x) ** 3
>>> min(1, '-3', '6', key=f)
'-3'

4.default关键字参数指定当可迭代对象为空时,返回的默认值。如果只传入的一个可迭代对象时,且可迭代对象为空,则必须指定命名参数default否则会报ValueError错误:

>>> min([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
>>> min([], default='None')
'None'
(3)max()

1.形式:

  • max(iterable, *[, key, default])
  • max(arg1, arg2, *args[, key])
>>> max(1, 9)
9
>>> max([1, 9])
9
>>> max('a', 'z')
'z'
>>> max([], default='None')
'None'
>>> max(-9, -2, -5, key=abs)
-9
(4)setattr(obj, name, value)

为对象设置属性名称和属性值。

参数:
  • object:实例化的对象名称;
  • name:属性名称;
  • value:属性值。

注意:属性名称name可以是一个已经存在的属性或一个新的属性。当该属性已经存在时,该方法会修改该属性值。

>>> class Stu:
...     pass
...
>>> s = Stu()
>>> setattr(s, 'name', 'Tom')
>>> s.name
'Tom'
>>> getattr(s, 'name')
'Tom'
>>> setattr(s, 'name', 'Jack')
>>> s.name
'Jack'
(5)getattr(obj, name[, default])

获取对象的属性值。
1.参数:

  • obj:实例化的对象名称;
  • name:属性名;
  • default:当该属性不存在时,默认返回的值。
>>> getattr(s, 'name')
'Jack'
>>> getattr(s, 'age', 'None')
'None'
(6)delattr(obj, name)

删除对象obj的name属性。

(7)hasattr(obj, name)

判断对象obj是否含有name属性。

(8)all(iterable)

当可迭代对象中的所有元素都为True或可迭代对象为空时,返回True。

>>> all([])
True
>>> all([1, 0])
False
>>> all([1, ''])
False
>>> all([1, 'ax', None])
False
>>> all([1, 'ax', ()])
False
(9)any(iterable)

当可迭代对象中至少有一个元素为True时返回True,否则返回False.

>>> any([])
False
>>> any([0, 0])
False
>>> any([0, 0, ''])
False
>>> any([0, 0, '', None])
False
>>> any([0, 0, '', None, ()])
False
>>> any([0, 0, '', None, (), 1])
True
(10)next(iterator[, default])

返回迭代器的下一个值。位置参数default指定当迭代器中的值耗尽时返回的默认值,如果没有指定则会抛出StopIteration异常。

>>> l = iter([1, 3, 5])
>>> next(l)
1
>>> next(l)
3
>>> next(l)
5
>>> next(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(l, 'None')
'None'
(11)divmod(a, b)

返回一个由a除以b的商和余数组成的元组,等价于(a//b, a%b)。

>>> divmod(3, 2)
(1, 1)
>>> divmod(5, 2)
(2, 1)
(12)sorted(iterable, *, key=None, reverse=False)

返回排序后的可迭代对象的列表。
参数:

  • key:指定在排序前对可迭代对象中的元素进行的操作;
  • reverse:表示排序的方式。reverse=False表示从小到大,reverse=True表示从大到小。
>>> sorted([1, 9, 6, 0])
[0, 1, 6, 9]
>>> sorted([1, 9, 6, 0], reverse=True)
[9, 6, 1, 0]
>>> def f(a):
...     return -a
...
>>> sorted([1, 9, 6, 0], key=f)
[9, 6, 1, 0]
>>> sorted((5, 9, 6, 1))
[1, 5, 6, 9]
(13)enumerate(iterable, start=0)

返回一个迭代器。该迭代器的元素为由索引和iterable的值组成的元组。
参数:

  • start:指定元组的索引的开始位置。
>>> enumerate(['Java', 'Python', 'PHP'])
<enumerate object at 0x0000000002580C60>
>>> for e in enumerate(['Java', 'Python', 'PHP']):
...     print(e)
...
(0, 'Java')
(1, 'Python')
(2, 'PHP')
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
(14)eval(expression, globals=None, locals=None)

返回执行了expression表达式后的结果。
参数:

  • expression:string类型,Python会将其转换为Python的表达式;
>>> x = 2
>>> eval('x + 3')
5
>>> eval('x * 3')
6
>>> eval('x ** 3')
8
(15)int(x=0)

将参数x转换为int类型的数据。如果没有提供参数,则返回0。如果x为浮点数,则只取其整数部分,且不对其进行四舍五入。
参数:x,number或string类型,默认为0。

>>> int('4')
4
>>> a = int()
>>> a
0
>>> int(3.45)
3
>>> int(3.65)
3
(16)open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

打开文件,返回一个文件对象。
参数:

  • file:文件路径;
  • mode:打开模式,默认为’r’,以‘只读’模式打开文本文件。
  • encoding:文件编码方式。

文件打开模式:

  • ‘r’:open for reading (default);
  • ‘w’:open for writing, truncating the file first;
  • ‘x’:open for exclusive creation, failing if the file already exists;
  • ‘a’:open for writing, appending to the end of the file if it exists;
  • ‘b’:binary mode;
  • ‘t’:text mode (default);
  • ‘+’:open a disk file for updating (reading and writing);
  • ‘U’:universal newlines mode (deprecated) 。
>>> with open('f.txt', 'r') as f:
...     for i in f.readlines():
...             print(i)
...
Java

Python

PHP
(17)isinstance(obj, classinfo)

判断对象obj是否是classinfo类型的实例。
参数:

  • obj:对象实例;
  • classinfo:类型,可以是一个有多个类型组成的元组。
>>> s = 'xzc'
>>> isinstance(s, str)
True>>> isinstance(s, (int, str))
True
>>> isinstance(s, (int, float))
False
(18)sum(iterable[, start])

计算可迭代对象中的所有值和start的和。
参数:

  • iterable:可迭代对象;
  • start:默认为0。
>>> sum([1, 3, 5])
9
>>> sum([1, 3, 5], 1)
10
(19)filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true。

>>> i = filter(f, [12, 5, '', None, 0])
>>> for x in i:
...     print(x)
...
12
5
(20)issubclass(class, classinfo):判断class是否是classinfo的子类。

注:

  • 一个类被认为是该类本身的子类;
  • classinfo可以是一个有类组成的元组。
>>> issubclass(str, (str, int))
True
>>> issubclass(str, str)
True
(21)pow(x, y[, z])

当z不存在时,返回x的y次方。当z存在时,求pow(x, y) % z)的值。

>>> pow(2, 3)
8
>>> pow(5, 3)
125
>>> pow(4, 2, 3)			#4**2%3
1
(22)iter(object[, sentinel])

当sentinel参数不存在时,object是一个集合,返回一个由该集合所有元素组成的迭代器。当sentinel参数存在时,object是一个可调用对象,当调用该对象计算后的值与sentinel相等时,抛出StopIteration 异常,否则返回该对象计算后的值。

>>> i = iter([1, 7, 9])
>>> for x in i:
...     print(x)
...
1
7
9

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)
(23)len(s)

返回序列的长度。

>>> len('asd')
3
>>> len('')
0
>>> len([1, 3, 6])
3
(24)zip(*iterables)

返回一个迭代器,由每一个可迭代对象中的元素联合组成的元组组成。当只有一个可迭代对象时,迭代器由单个元素的元组组成。

>>> it = zip([1, 3], ('x', 'y'))
>>> list(it)
[(1, 'x'), (3, 'y')]
>>> it = zip([1, 3], ('x', 'y', 'k'))
>>> list(it)
[(1, 'x'), (3, 'y')]
>>> it = zip(('x', 'y'))
>>> list(it)
[('x',), ('y',)]
(25)round(number[, ndigits])

当没有提供ndigits参数时,返回number四舍五入后的整数值。当提供ndigits参数时,返回保留小数点后ndigits位且四舍五入后的数字。

>>> round(3.45)
3
>>> round(3.75)
4
>>> round(3.75, 1)
3.8
>>> round(3.75, 2)
3.75
>>> round(3.75, 3)
3.75
(26)set([iterable])

返回由可迭代对象中的元素组成的set 集合,去除重复的元素。

>>> s = set(['Java', 'PHP'])
>>> type(s)
<class 'set'>
>>> list(s)
['Java', 'PHP']
(27)frozenset([iterable])

返回由可迭代对象中的元素组成的frozenset 集合,去除重复的元素。

(28)map(func, iterable, …)

返回可迭代对象中所有经过函数func计算后的结果组成的迭代器。
注:函数func的参数个数要和迭代对象的个数对应。当迭代对象的长度不一致时,只计算到最短的那个。

>>> it = map(abs, [3, -9, -7])
>>> list(it)
[3, 9, 7]
>>> f = lambda x, y: x + y
>>> it = map(f, [3, -9, -7], [2, 0])
>>> list(it)
[5, -9]
(29)range(stop) 或 range(start, stop[, step])
1.参数
  1. start:默认为0。如果
  2. stop:
  3. step:默认为1。如果step=0,则抛出ValueError 异常。当step>0时,依次产生值r[i] = start + stepi,约束条件为 i>= 0 and r[i] < stop;当step<0时,任然产生值 r[i] = start + stepi,但是约束条件变为 i>= 0 & r[i] > stop
>>> r = range(5)
>>> type(r)
<class 'range'>
>>> list(r)
[0, 1, 2, 3, 4]
>>> r = range(1, 5)
>>> list(r)
[1, 2, 3, 4]
>>> r = range(1, 5, 2)
>>> list(r)
[1, 3]
>>> list(range(0, -10, 2))
[]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值