python内置函数

python内置函数

内置函数共有68个,分成六类

  1. 作用域相关:2个
  2. 面向对象相关:9个
  3. 基础数据类型相关:38个
  4. 迭代器生成器相关:3个
  5. 反射相关:4个
  6. 其他:12个

一、作用域相关

  globals()  获取全局变量的字典

  locals()     获取执行本方法所在命名空间内的局部变量的字典

二、其他

  字符串类型代码的执行

    eval()  讲字符串类型的代码 执行并返回结果  

    exec()  将自字符串类型的代码执行

# eval()
print(eval("1 + 2 + 3 + 4"))



# exec()
print(exec("1 + 2 + 3 + 4"))
exec('print("hello world")')

code = '''
import os
print(os.path.abspath('.'))
'''
code = '''
print(123)
a = 20
print(a)
'''
a = 10
exec(code,{'print':print},)
print(a)

 

    compile()  将字符串类型的代码编译,代码对象能够通过exec语句执行或者eval()进行求值。

#compile()
#参数说明:
# 参数sourse:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段
# 参数filename:代码文件名称,如果不是从文件读取代码则 传递一些可辨认的值,当传入了# sourse参数时,filename参数传入空字符即可
# 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指#定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'

>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
1
3
5
7
9


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)


>>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"

  输入输出

    input()

s = input("请输入内容:")    # 将输入的内容赋值给变量S
print(s)        输出什么打印什么。数据类型为str

    print()

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
    sep:   打印多个值之间的分隔符,默认为空格
    end:   每一次打印的结尾,默认为换行符
    flush: 立即把内容输出到流文件,不作缓存
    """

print源码剖析
import time
for i in range(0,101,2):
    time.sleep(0.1)
    char_num = i//2
    pre_str = '\r%s%% : %s\n' % (i,'*'* char_num) if i ==100 else '\r%s%% : %s'%(i,'*'*char_num)
    print(pre_str,end = '',flush = True)
打印进度条

  内存相关

    hash()

# hash(o):o为参数,返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错

t = (1,2,3)
l = [1,2,3]
print(hash(t))    #可哈希
print(hash(l))    #会报错

# hash函数会根据一个内部的算法对当前可hash变量进行处理,返回一个int数字
# 每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变
hash实例

    id()

    返回一个变量的内存地址

  文件操作相关

    open()

# open()打开文件,返回一个文件操作符

filename = 'test.txt'
f = open(filename,'r')

#操作文件的模式有r w a r+ w+ a+,每一种方式都可以使用二进制形式操作在操作模式前+r

  模块相关

    __import__

#导入模块
import os


os = __import__('os')
print(os.path.abspath('.'))

  帮助

    help()

#在控制台执行help()进入帮助模式。可以随意输入变量或者变量的类型。输入q退出

#或者直接执行help(o),o是参数,查看和变量o有关的操作。。。

  调用相关

    callable()

#callable(o),o是参数,看这个变量是不是可调用
#如果 o 是函数名就会返回True

def func():pass
print(callable(func))    #参数是函数名,可调用,返回True
print(callable(123))    # 参数是数字,不可调用,返回False

 

  查看内置属性

    dir()  默认查看全局空间内的属性,也接受一个参数,查看这个参数内的方法或变量

print(dir(list))    #查看列表的内置方法
print(dir(int))    #查看整数的内置方法

三、与数字相关

  1、数据类型

    bool()

    int()

    float()

    complex()

  2、进制转换

    bin()  2进制

    oct()  8进制

    hex()  16进制

  3、数学运算

    abs()  绝对值

    divmod()  返回(除,余)

    round()  小数精确

    pow()  幂运算

    sum()  求和

    min()  计算最小值

    max()  计算最大值

四、与数据结构相关

  1、序列

    列表和元组相关:list、tuple

    字符串相关的:str、format、bytes、bytearry、memoryview、ord、chr、ascii、repr

    

# bytearray
ret = bytearray('alex',encoding = 'utf-8')
print(id(ret))
print(ret[0])
ret[0] = 65
print(ret)
print(id(ret))


#memotyview
ret = memoryview(bytes('你好',encoding='utf-8'))
print(len(ret))
print(bytes(ret[:3]).decode('utf-8'))
print(bytes(ret[3:]).decode('utf-8'))

 

    相关内置函数:reversed、slice

#reversed

l = (1,2,23,213,5612,243,42)
print(l)
print(list(reversed(l)))


#slice

l = (1,2,23,213,5612,243,42)
sli = slice(1,5,2)
print(l[sli])  

  2、数据集合

    字典:dict

    集合:set、frozenset

  3、相关内置函数

    len、sorted、enumerate、all、any、zip、filter、map

#filter
#filter()函数接受一个函数f和一个list,
#函数f是对列表中的每个元素经行判断,返回True或False
#filter()根据判断结果自动过滤掉不符合的元素,返回由符合条件元素组成的新list

def is_odd(x):
    return x%2 ==1

L = fiter(is_odd,[1,4,5,6,,9,12,17])
ptint(list(L))

#利用filter()过滤出1~100中平方根是整数的数
import math
def is_pex(x):
    retuen math.sqrt(x) % 1 == 0
print(list(filter(is_pex,range(1,101)))
#map
#map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回

#有一个list,L=[1,2,3,4,5,6,7,8]
L = [x for x in range(1,9)]
def pow2(x):
    return x*x
print(list(map(pow2,L)))
                                                                                                                           
对list、Dict进行排序,两个方法                                                                                                        
 方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本                                                                                      
 方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变                                                                             
 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 customise the sort order, and the                                                
 reverse flag can be set to request the result in descending order.                                                        
                                                                                                                           
 参数说明:                                                                                                                     
 iterable:是可迭代类型                                                                                                           
 key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序                                                                                 
 reverse:排序规则. reverse = True  降序 或者 reverse = False 升序,有默认值。                                                              
 返回值:有序列表                                                                                                                  
                                                                                                                           
 列表按照其中每一个值的绝对值排序                                                                                                          
1 = (1,3,5,-2,-4,-6)                                                                                                       
2 = sorted(L1,key=abs)                                                                                                     
rint(L1)                                                                                                                   
rint(L2)                                                                                                                   
                                                                                                                           
 列表按照每一个元素的len排序                                                                                                           
 = [[1,2],[3,4,5,6],(7,),'123']                                                                                            
rint(sorted(L,key = len))                                                                                                  
                                                                                                                           
View Code

 

  

转载于:https://www.cnblogs.com/cjj426890/p/9927914.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值