Python内置函数

目录

abs

all

any

ascii

bin

bool

breakpoint

bytearray

bytes

callable

chr

classmethod

compile

complex

credits

delattr

dict

dir

divmod

enumerate

eval

exec

exit

filter

float

format

frozenset

getattr

globals

hasattr

hash

help

hex

id

input

int

isinstance

issubclass

iter

len

license

list

locals

map

max

memoryview

min

next

object

oct

open

ord

pow

property

quit

range

repr

reversed

round

set

setattr

slice

sorted

staticmethod

str

sum

super

tuple

type

vars

zip


dir(__builtins__) 可以看到 Python 提供的内置方法列表。
help(BIF)查看函数说明。
参考资料:http://www.runoob.com/python3/python3-built-in-functions.html

abs

 

all

 

any

 

ascii

 

bin

 

bool

 

breakpoint

 

bytearray

 

bytes

 

callable

 

chr

 

classmethod

 

compile

 

complex

 

 

credits

 

delattr

 

dict

 

dir

 

divmod

 

enumerate

enumerate(iterable):生成由二元组(元素数量为二的元组)构成的一个迭代对象,每个二元组是由迭代参数的索引号及其对应的元素构成。

>>> list1 = [2, 9, -10, 8, 17, 3]
>>> enumerate(list1)
<enumerate object at 0x03565E68>    #返回迭代器对象
>>> list(enumerate(list1))
[(0, 2), (1, 9), (2, -10), (3, 8), (4, 17), (5, 3)]    # (索引号, 元素)

eval

语法:eval(expression[, globals[, locals]]) ;用来执行一个字符串表达式,并返回表达式的值。
expression -- 表达式。
globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

>>> '3 * 2'
'3 * 2'
>>> eval('3 * 2')
6

>>> a = '2 + 2'
>>> print(a)
2 + 2
>>> eval(a)
4

>>> eval('2 + 2')
4

>>> x = 7
>>> eval('3 * x')
21

>>> eval('pow(2, 2)')
4

exec

 

exit

 

filter

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象。如果要转换为列表,可以使用 list() 来转换。

语法:filter(function or None, iterable)
function -- 判断函数。
iterable -- 可迭代对象(序列)。

如果第一个为 None,则直接将第二个参数中为 True 的元素筛选出来。

temp = filter(None, [1, 0, False, True])    #第一个为None,直接选True
print(temp)    #返回对象
print(list(temp))

'''
<filter object at 0x00840CB0>
[1, True]
'''

如果第一个为函数(function),第二个为序列。序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

例:筛选奇数的过滤器

def odd(x):
    return x % 2    #求余。偶数为0,奇数为1。

temp = range(10)    #0~9
show = filter(odd, temp)    #过滤器
print(list(show))

# 以上所有可用一行lambda函数实现:
# print(list(filter(lambda x : x % 2, range(10))))
'''
[1, 3, 5, 7, 9]
'''

float

将一个字符串或整数转换成一个浮点数。

>>> a = '123'	#字符串
>>> float(a)
123.0

>>> a = 123	#整数
>>> float(a)
123.0

format

 

frozenset

不可变集合

>>> set0 = frozenset({1, 2, 3, 4, 5})
>>> set0.add(6)    #无法添加,报错
Traceback (most recent call last):
  File "<pyshell#209>", line 1, in <module>
    set0.add(6)
AttributeError: 'frozenset' object has no attribute 'add'

 

getattr

 

globals

 

hasattr

 

hash

 

help

 

hex

 

id

 

input

接收任意输入,将所有输入默认为字符串处理,并返回字符串类型。

>>> a = input('input:')
input:123
>>> type(a)
<class 'str'>
>>> 
>>> a = input('input:')
input:abc
>>> type(a)
<class 'str'>
line = '这是第1行,请在第3行输入姓名…'
line += '\n这是第2行,在第3行请输入姓名…'
line += '\n这是第3行,请输入姓名:'

name = input(line)

'''
这是第1行,请在第3行输入姓名…
这是第2行,在第3行请输入姓名…
这是第3行,请输入姓名:
'''

int

将一个字符串或浮点数转换为一个整数。

>>> a = int('520')	#字符串
>>> a
520

>>> a = int(0.618)	#浮点数。不是四舍五入,只取整。
>>> a
0

>>> a = int(3.5)
>>> a
3

isinstance

 

issubclass

 

iter

 

len

len(sub)用于返回sub参数的长度:

>>> len('ab')    #字符串长度
2

>>> str1 = 'abc'
>>> len(str1)    #字符串长度
3

>>> a = list()    #a是一个空列表
>>> len(a)
0

>>> list1 = [7, 8, 9,10]
>>> len(list1)    #列表长度
4

>>> tuple1 = '一', '二', '三', '四'
>>> len(tuple1)    #元组长度
4

>>> set1 = set(('AA', 'BB', 'CC', 'DD'))
>>> len(set1)    #集合长度
4
>>> list2=list(range(5))    #创建一个 0-4 的列表
>>> print (len(list2))
5

license

 

list

list(iterable):把可迭代对象转换为列表。用法与tuple()一样。

>>> a = list()
>>> a    #空列表
[]

>>> b='abcdefg'
>>> b=list(b)
>>> b
['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> list('a b c')
['a', ' ', 'b', ' ', 'c']

>>> c = (1, 1, 2, 3, 5, 8, 13, 21, 34)
>>> c = list(c)    #元组变成列表
>>> c
[1, 1, 2, 3, 5, 8, 13, 21, 34]
aTuple = (123, 'Google', 'Runoob', 'Taobao')
list1 = list(aTuple)    #元组转换列表
print (list1)

输出结果:
[123, 'Google', 'Runoob', 'Taobao']
str="Hello World"
list2=list(str)    #字符串转换列表
print (list2)

输出结果:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> f = open('D:\\Python\\暂存练习test\\filetest.txt')
>>> list(f)    # 文件对象转化为列表
['1234567890\n', 'ABCDEFGHIJ\n', 'あいうえおかきくけこ']

locals

 

map

语法:map(function, iterable, ...)
function -- 函数
iterable -- 一个或多个序列

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

print(list(map(lambda x : x * 2, range(10))))

'''
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
'''

max

max()方法返回序列或者参数集合中的最大值。序列或参数的数据类型须统一,否则会出错。

>>> max(5, 6, 7, -8)
7

>>> max("love")
'v'

>>> list1 = [5, 6, 7, -8]
>>> max(list1)
7

>>> tuple1 = 'see', 'you', 'zoo', 'later'
>>> max(tuple1)
'zoo'
​list1, list2 = ['Google', 'Runoob', 'Taobao'], [456, 700, 200]
print (max(list1))
print (max(list2))

输出结果:
Taobao
700

memoryview

 

min

min()方法返回序列或者参数集合中的最小值。序列或参数的数据类型须统一,否则会出错。

>>> min(5, 6, 7, -8)
-8

>>> min('love')
'e'

>>> list1 = [5, -2, 7, -8]
>>> min(list1)
-8

>>> tuple1 = 'see', 'you', 'zoo', 'later'
>>> min(tuple1)
'later'
list1, list2 = ['Google', 'Runoob', 'Taobao'], [456, 700, 200]
print (min(list1))
print (min(list2))

输出结果:
Google
200

next

 

object

 

oct

 

open

 

ord

 

pow

返回(x的y次方)的值。

1、math 模块 pow() 方法的语法:

import math
math.pow(x, y)

math 模块则会把参数转换为 float。 

import math   # 导入 math 模块
print ("math.pow(100, 2) :", math.pow(100, 2))

print ("math.pow(100, -2) :", math.pow(100, -2))

print ("math.pow(2, 4) :", math.pow(2, 4))

print ("math.pow(3, 0) :", math.pow(3, 0))

'''输出结果:
math.pow(100, 2) : 10000.0
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0
'''

2、内置的 pow() 方法:
如果z在存在,则再对结果进行取模,其结果等效于 pow(x, y) % z。通过内置的方法直接调用,内置方法会把参数作为整型 。

pow(x, y[, z])
>>> print ("pow(100, 2) :", pow(100, 2))
pow(100, 2) : 10000

print

>>> print('Hello!')
Hello!

>>> message = 'A'
>>> print(message)
A
#下例同时为Python字符串运算范例
>>> a, b = 'hello', 'world'
>>> print(a + b)    #+号连接字符串
helloworld
>>> print(a * 2)    #*号重复字符串
hellohello
>>> print(a[1])    #[]索引字符
e
>>> print(a[1:4])    #[:]截取字符串
ell
>>> print('h' in a)    #in是否包含
True
>>> print('M' not in a)    #not in是否不包含
True
>>> print(r'\n')    #r/R原始字符串(不解析转义字符)
\n

访问列表元素(以下方法同样适用于元组,两者语法相同):

>>> name = ['Tom', 'Jack', 'Nick', 'John']
>>> print(name[1])    #获取列表元素时,没有方括号和引号
Jack
>>> print(name[1].upper())    #加入字符串方法
JACK
>>> print('My boyfriend is ' + name[0].upper() + '.')    #索引0为第一项
My boyfriend is TOM.
>>> print(name[-1])    #-1返回最后一个,-2倒数第二个,以此类推
John
>>> print(name[1:3])    #索引1~2项
['Jack', 'Nick']
>>> print(name[:3])    #索引0~2项
['Tom', 'Jack', 'Nick']
>>> print(name[1:])    #索引1~最后
['Jack', 'Nick', 'John']
>>> print(name[-3:])    #最后三个
['Jack', 'Nick', 'John']
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];

print ("list1[0]: ", list1[0])
print ("list1[-1]: ", list1[-1])    #列表如为空这样访问会出错
print ("list2[1:5]: ", list2[1:5])

输出结果:
list1[0]:  Google
list1[-1]:  2000
list2[1:5]:  [2, 3, 4, 5]
list = [1, 2, 3, ['a', 'b', 'c'], 4]    #列表中包含列表元素
print(list[3][1])    #索引3中的索引1

输出结果:
b
#        0    1    2    3    4    5    6
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
#       -7   -6   -5   -4   -3   -2   -1

print(list[0:3:2])	#1 索引0到索引3,步长2
print(list[::2])	#2 整个列表步长2
print(list[0:-4])	#3 不包括后边索引本身
print(list[0:-5])	#4 同上
print(list[-7:-5])	#5 同上
print(list[::-1])	#6 步长-1,相当于复制一个反转列表
print(list[4:0:-1])	#7 步长如为负,end:start:step,不包括后边索引
print(list[-4:0:-1])	#8 同上
print(list[-1:-4:-1])	#9 同上

输出结果:
['a', 'c']	#1
['a', 'c', 'e', 'g']	#2
['a', 'b', 'c']	#3
['a', 'b']	#4
['a', 'b']	#5
['g', 'f', 'e', 'd', 'c', 'b', 'a']	#6
['e', 'd', 'c', 'b']	#7
['d', 'c', 'b']	#8
['g', 'f', 'e']	#9

print() 函数的参数:print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

sep:在值之间插入字符串,默认为空格。

>>> print('Abc', 'Def', 'Ghi')    #默认空格,等价 sep=' '
Abc Def Ghi

>>> print('Abc', 'Def', 'Ghi', sep='')    #删除sep空格
AbcDefGhi

>>> print('Abc', 'Def', 'Ghi', sep='***')
Abc***Def***Ghi

>>> print('Abc', 'Def', 'Ghi', sep='\n')
Abc
Def
Ghi

>>> print('Abc', 'Def', 'Ghi', sep='\n***')
Abc
***Def
***Ghi

end:在最后的值后加入字符,默认是换行。 

print('123', '456')    # 等价: end = '\n'
print('Abc', 'Def')    # 等价: end = '\n'

'''输出结果:
123 456
Abc Def
'''
print('123', '456', end = ' ')    #空格
print('Abc', 'Def')

'''
输出结果:
123 456 Abc Def
'''
print('123', '456', end = '***')
print('Abc', 'Def', end = '###')

'''
输出结果:
123 456***Abc Def###
'''

property

 

quit

 

range

range([start,] stop[, step]) 返回的是一个可迭代对象(类型是对象,而不是列表类型), 所以打印的时候不会打印列表。它生成一个从 start 参数的值开始(默认从 0 开始),到 stop 参数的值结束(但不包括 stop),步长 step(默认为1)的数字序列,经常与 for 循环一起使用。

>>> range(5)
range(0, 5)
>>> for i in range(5):
	print(i)

0
1
2
3
4
#使用range()函数来创建一个列表
>>> list(range(0))
[]

>>> list(range(1, 0))
[]

>>> list(range(5))    # range(0, 5, 1)
[0, 1, 2, 3, 4]

>>> list(range(12, 18, 2))
[12, 14, 16]

>>> list(range(0, -6, -1))
[0, -1, -2, -3, -4, -5]

>>> list(range(0, -6, -2))
[0, -2, -4]
>>> numbers = list(range(1, 5))
>>> print(numbers)
[1, 2, 3, 4]

repr

 

reversed

reversed(sequence):用于返回逆向迭代序列的值。实现效果与列表内建方法 reverse() 一致。区别:内建方法 reverse() 是原地翻转(见:《Python列表-list.reverse()》),而 reversed() 是返回一个翻转后的迭代器对象。

>>> list1 = [2, 9, -10, 8, 17, 3]
>>> reversed(list1)
<list_reverseiterator object at 0x030458B0>    #翻转后的迭代器对象
>>> list(reversed(list1))
[3, 17, 8, -10, 9, 2]

round

 

set

创建一个无序的不重复元素序列——集合。见《Python集合

setattr

 

slice

 

sorted

sorted(iterable, key = None, reverse = False);对所有可迭代的对象进行排序操作。

参数说明:
iterable -- 可迭代对象。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

sort 与 sorted 区别(sort见:《Python列表-方法-list.sort(cmp=None, key=None, reverse=False)》)
sort 是应用在 list 上的方法(list.sort() 方法只为 list 定义),sorted 可以对所有可迭代的对象进行排序操作(sorted() 函数可以接收任何的 iterable)
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

>>> sorted('hello')
['e', 'h', 'l', 'l', 'o']
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]   
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})    # sorted()函数可以接收任何的 iterable
[1, 2, 3, 4, 5]
>>> example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> result_list = sorted(example_list, key=lambda x: x*-1)    #利用key进行倒序排序
>>> print(result_list)
[7, 6, 5, 4, 3, 2, 1, 0]
>>> example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> sorted(example_list, reverse=True)    #反向排序
[7, 6, 5, 4, 3, 2, 1, 0]
#对列表排序
>>> list1 = [2, 9, -10, 8, 17, 3]
>>> list2 = list1[:]
>>> list1.sort()    #方法sort没有返回值,实现列表原地永久性排序,无法返回。
>>> list1
[-10, 2, 3, 8, 9, 17]
>>> sorted(list2)    #函数sorted排序后返回排序后的新列表。
[-10, 2, 3, 8, 9, 17]
>>> list2    #排序后原列表不变。
[2, 9, -10, 8, 17, 3]

staticmethod

 

str

str(obj)方法用于把obj对象转为字符串

>>> str(0.01)
'0.01'
>>> age = 21
>>> message = 'Happy ' + str(age) + 'st Birthday!'    #不变类型会出错,数字+字符。
>>> print(message)
Happy 21st Birthday!

sum

sum(iterable[, start])方法用于返回序列 iterable 的总和。如果没有设置可选参数(start),默认为0,表示从该值开始加起。

>>> tuple1 = 1.1, 2.2, 0.3
>>> sum(tuple1)
3.6

>>> tuple2 = 1, 2, 3, 4, 5
>>> sum(tuple2)
15
>>> sum(tuple2, 8)    # 8+(1+2+3+4+5)
23
>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> sum(list1)
45
>>> sum(list1, 5)    # 5 + sum(list1)
50

super

 

tuple

tuple([iterable]):把可迭代对象转换为元组.用法与list()一样。

>>> a = tuple()    #tuple():空元组
>>> a
()

>>> b='abcdefg'
>>> b=tuple(b)
>>> b
('a', 'b', 'c', 'd', 'e', 'f', 'g')

>>> tuple('a b c')
('a', ' ', 'b', ' ', 'c')

>>> c = [1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> c = tuple(c)    #列表变成元组
>>> c
(1, 1, 2, 3, 5, 8, 13, 21, 34)

type

 

vars

 

zip

zip(iter1[, iter2[...]]):返回由各个可迭代参数共同组成的元组。

>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> b = ['a', 'b', 'c', 'd']
>>> c = 'today'

>>> zip(a, b)
<zip object at 0x02ED03A0>    #返回迭代器对象
>>> list(zip(a, b))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

>>> list(zip(a, c))
[(1, 't'), (2, 'o'), (3, 'd'), (4, 'a'), (5, 'y')]

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值