内置函数

内置函数

  Built-in Functions  
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()

作用域相关

globals() ————获取全局变量

locals()   ————获取本地命名空间内的局部变量

字符串类型代码的执行

# exec('print(123)')
# eval('print(123)')
# print(eval('1+2+3+4')) # 有返回值
# print(exec('1+2+3+4')) #没有返回值
# exec和eval都可以执行 字符串类型的代码
# eval有返回值 —— 有结果的简单计算
# exec没有返回值 —— 简单流程控制
# eval只能用在你明确知道你要执行的代码是什么
View Code
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()进行求值。
参数说明:   

1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

3. 参数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'"
eval , exce , compile

输入输出相关

input() 输入

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

print()输出

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

文件操作

open

文件操作相关

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

操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+)

可以用encoding指定编码.

f = open('tmp_file','w')
print(123,456,sep=',',file = f,flush=True)
View Code

模块相关

import

import os
import time
……
View Code
import time
for i in range(0,101,2):  
     time.sleep(0.1)
     char_num = i//2      #打印多少个'*'
     per_str = '
%s%% : %s
' % (i, '*' * char_num) if i == 100 else '
%s%% : %s'%(i,'*'*char_num)
     print(per_str,end='', flush=True)
# 
 可以把光标移动到行首但不换行

打印进度条
View Code

内存相关

id(o) o是参数,返回一个变量的内存地址

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

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

'''
结果:
TypeError: unhashable type: 'list'
'''

hash实例
View Code

hash函数会根据一个内部的算法对当前可hash变量进行处理,返回一个int数字。

*每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变。

帮助方法

help()

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

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

迭代器生成器相关

inter

next

range

#迭代器.__next__()
# next(迭代器)
# 迭代器 = iter(可迭代的)
# 迭代器 = 可迭代的.__iter__()

# range(10)
# range(1,11)
# print('__next__' in dir(range(1,11,2)))
#range是可迭代的
View Code

调用相关

callable(o),o是参数,看这个变量是不是可调用。

如果o是一个函数名,就会返回True

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

查看参数所属类型的所有内置方法

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

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

数据类型相关

type(o) 返回变量o的数据类型

print(type({}))
#————<class 'dict'>
View Code

 和数字相关

数字——数据类型相关:bool,int,float,complex

complex 复数

实数 : 有理数
无理数
虚数 :虚无缥缈的数
5     +    12j === 复合的数 === 复数
实部  + 虚部

数字——进制转换相关:bin,oct,hex

print(bin(1)) #——0b1 #二进制

print(oct(1)) #——0o1 #十进制

print(hex(1))#——0x1  #十六进制
View Code

数字——数学运算:abs(绝对值),divmod(除,余),min(最小),max(最大),sum(求和),round(小数精确),pow(幂运算)

print(abs(-4))  #—— 4

print(divmod(7,2)) #—— (3,1)  #7/2商3余1 

print(min(7,2)) #—— 2
print(min(1,2,3,-4,key = abs))#——1#根据绝对值取最小值

print(max(7,2))#—— 7
print(max(1,2,3,-4,key = abs))#——-4#根据绝对值取最大值

print(sum([7,2]))#—— 9 #sum后面跟的是可迭代数据类型

print(round(3.1415926))#—— 3
print(round(3.1415926,3))#——3.142
print(round(3.1415926,4))#——3.1416

print(pow(2,3))#—— 8 #2的3次方
print(pow(3,2,4)) #——1#3的平方之后再对4取余 
View Code

和数据结构相关

序列——列表和元组相关的:list和tuple

串相关的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr

ord() 字符按照unicode转数字

chr() 数字按照Unicode转字符

ascii() 只要是ascii码中的内容,就打印出来,不是就转成u

bytearry()    bytearry(s,encoding = "utf-8")

bytes()      bytes(s,encoding ="utf-8")

ret = bytearray('alex',encoding='utf-8')
print(id(ret))
print(ret[0])
ret[0] = 65
print(ret)
print(id(ret))
View Code
ret = memoryview(bytes('你好',encoding='utf-8'))
print(len(ret))
print(bytes(ret[:3]).decode('utf-8'))
print(bytes(ret[3:]).decode('utf-8')

#bytes 转换成bytes类型
# 我拿到的是gbk编码的,我想转成utf-8编码
# print(bytes('你好',encoding='GBK'))     # unicode转换成GBK的bytes
# print(bytes('你好',encoding='utf-8'))   # unicode转换成utf-8的bytes
View Code
说明:

 

  1. 函数功能将一个数值进行格式化显示。

  2. 如果参数format_spec未提供,则和调用str(value)效果相同,转换成字符串格式化。

>>> format(3.1415936)
'3.1415936'
>>> str(3.1415926)
'3.1415926'
  3. 对于不同的类型,参数format_spec可提供的值都不一样

复制代码
#字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))

#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #转换成二进制
'11'
>>> format(97,'c') #转换unicode成字符
'a'
>>> format(11,'d') #转换成10进制
'11'
>>> format(11,'o') #转换成8进制
'13'
>>> format(11,'x') #转换成16进制 小写字母表示
'b'
>>> format(11,'X') #转换成16进制 大写字母表示
'B'
>>> format(11,'n') #和d一样
'11'
>>> format(11) #默认和d一样
'11'

#浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') #科学计数法,默认保留6位小数
'3.141593e+08'
>>> format(314159267,'0.2e') #科学计数法,指定保留2位小数
'3.14e+08'
>>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示
'3.14E+08'
>>> format(314159267,'f') #小数点计数法,默认保留6位小数
'314159267.000000'
>>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数
'3.141593'
>>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数
'3.14159267'
>>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数
'3.1415926700'
>>> format(3.14e+1000000,'F')  #小数点计数法,无穷大转换成大小字母
'INF'

#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
'3.14'
>>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'
format

repr()  会让一个变量原封不动的输出出来,用于%r

name = 'egg'
print('你好%s'%name) #——你好egg
print('你好%r'%name)#——你好“egg"
print(repr('1'))#——’1‘
print(repr(1))#——1
repr

序列:reversed,slice

# reversed()
# l = [1,2,3,4,5]
# l.reverse()
# print(l)
# l = [1,2,3,4,5]
# l2 = reversed(l)
# print(l2)
# 保留原列表,返回一个反向的迭代器
View Code
l = (1,2,23,213,5612,342,43)
sli = slice(1,5,2)
print(l[sli])  ==  print(l[1:5:2])
View Code

数据集合——字典和集合:dict,set,frozenset

frozenset 不可变的集合,可作为字典的Key值

数据集合:len,sorted,enumerate,all,any,zip,filter,map

# print(all(['a','',123])) #——False
# print(all(['a',123]))   #——Ture
# print(all([0,123]))     #——False
  有一个数据类型是False 他就是False 全是Ture才是Ture

# print(any(['',True,0,[]]))   #——Ture
有一个数据类型是Ture  就是Ture
all any
# l = [1,2,3,4,5]
# l2 = ['a','b','c','d']
# l3 = ('*','**',[1,2])
# d = {'k1':1,'k2':2}
# for i in zip(l,l2,l3,d):
#     print(i)
---------------
(1, 'a', '*', 'k1')
(2, 'b', '**', 'k2')

拉链方法  
zip

filter 执行了filter之后的结果集合 <= 执行之前的个数 
filter只管筛选,不会改变原来的值
map 执行前后元素个数不变 值可能发生改变

filter

filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

例如,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:

def is_odd(x):
    return x % 2 == 1
然后,利用filter()过滤掉偶数:

>>>list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))
结果:

[1, 7, 9, 17]
利用filter(),可以完成很多有用的功能,例如,删除 None 或者空字符串:

def is_not_empty(s):
    return s and len(s.strip()) > 0
>>>list(filter(is_not_empty, ['test', None, '', 'str', '  ', 'END']))
结果:

['test', 'str', 'END']
注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。

当rm为空时,默认删除空白符(包括'
', '
', '	', ' '),如下:

>>> a = ' 123'
>>> a.strip()
'123'

>>> a = '		123
'
>>> a.strip()
'123'

练习:

请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

方法:

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
print(list(filter(is_sqr, range(1, 101))))
结果:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
map

Python中的map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。

有一个list, L = [1,2,3,4,5,6,7,8],我们要将f(x)=x^2作用于这个list上,那么我们可以使用map函数处理。

>>> L = [1,2,3,4,] 
>>> def pow2(x): 
... return x*x 
... 
>>> list(map(pow2,L))
[1, 4, 9, 16] 
filter, map
对List、Dict进行排序,Python提供了两个方法
对给定的List L进行排序,
方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本
方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变

--------------------------------sorted---------------------------------------
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 升序,有默认值。
返回值:有序列表
 
例:
列表按照其中每一个值的绝对值排序

l1 = [1,3,5,-2,-4,-6]
l2 = sorted(l1,key=abs)
print(l1)
print(l2)
 

列表按照每一个元素的len排序


l = [[1,2],[3,4,5,6],(7,),'123']
print(sorted(l,key=len))
sorted

匿名函数


# min max filter map sorted —— lambda

匿名函数:为了解决那些功能很简单的需求而设计的一句话函数

#这段代码
def calc(n):
    return n**n
print(calc(10))
 
#换成匿名函数
calc = lambda n:n**n
print(calc(10))
View Code

上面是我们对calc这个匿名函数的分析,下面给出了一个关于匿名函数格式的说明

函数名 = lambda 参数 :返回值

#参数可以有多个,用逗号隔开
#匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
#返回值和正常的函数一样可以是任意数据类型

我们可以看出,匿名函数并不是真的不能有名字。

匿名函数的调用和正常的调用也没有什么分别。 就是 函数名(参数) 就可以了~~~

练一练:

请把以下函数变成匿名函数
def add(x,y):
    return x+y
 

上面是匿名函数的函数用法。除此之外,匿名函数也不是浪得虚名,它真的可以匿名。在和其他功能函数合作的时候

复制代码
l=[3,2,100,999,213,1111,31121,333]
print(max(l))

dic={'k1':10,'k2':100,'k3':30}


print(max(dic))
print(dic[max(dic,key=lambda k:dic[k])])
复制代码
复制代码
res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
    print(i)

输出
1
25
49
16
64
复制代码
复制代码
res = filter(lambda x:x>10,[5,8,11,9,15])
for i in res:
    print(i)

输出
11
15
View Code
1.下面程序的输出结果是:
d = lambda p:p*2
t = lambda p:p*3
x = 2
x = d(x)
x = t(x)
x = d(x)
print x

2.现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

3.以下代码的输出是什么?请给出答案并解释。
def multipliers():
    return [lambda x:i*x for i in range(4)]
print([m(2) for m in multipliers()])
请修改multipliers的定义来产生期望的结果。
# d = lambda p:p*2
# t = lambda p:p*3
# x = 2
# x = d(x) #x = 4
# x = t(x) #x = 12
# x = d(x) #x = 24
# print(x)

# ret = zip((('a'),('b')),(('c'),('d')))
# ret = map(lambda t:{t[0]:t[1]},ret)
# print(list(ret))

#现有两元组(('a'),('b')),(('c'),('d')),
# 请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

# max min sorted filter map
# 匿名函数 == 内置函数
# zip
# ret = zip((('a'),('b')),(('c'),('d')))
# res = map(lambda tup:{tup[0]:tup[1]},ret)
# print(list(res))

# def multipliers():
#     return [lambda x:i*x for i in range(4)]
# print([m(2) for m in multipliers()])
View Code
# 3.用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
name=['alex','wupeiqi','yuanhao','nezha']
# def func(item):
#     return item+'_sb'
# ret = map(func,name)   #ret是迭代器
# for i in ret:
#     print(i)
# print(list(ret))

# ret = map(lambda item:item+'_sb',name)
# print(list(ret))

# 4.用filter函数处理数字列表,将列表中所有的偶数筛选出来
# num = [1,3,5,6,7,8]
# def func(x):
#     if x%2 == 0:
#         return True
# ret = filter(func,num)  #ret是迭代器
# print(list(ret))
#
# ret = filter(lambda x:x%2 == 0,num)
# ret = filter(lambda x:True if x%2 == 0 else False,num)
# print(list(ret))

# 5.随意写一个20行以上的文件
# 运行程序,先将内容读到内存中,用列表存储。
# 接收用户输入页码,每页5条,仅输出当页的内容

# with open('file',encoding='utf-8') as f:
#     l = f.readlines()
# page_num = int(input('请输入页码 : '))
# pages,mod = divmod(len(l),5) #求有多少页,有没有剩余的行数
# if mod:           # 如果有剩余的行数,那么页数加一
#     pages += 1    # 一共有多少页
# if page_num > pages or page_num <= 0:   #用户输入的页数大于总数或者小于等于0
#     print('输入有误')
# elif page_num == pages and mod !=0:    #如果用户输入的页码是最后一页,且之前有过剩余行数
#     for i in range(mod):
#         print(l[(page_num-1)*5 +i].strip())  #只输出这一页上剩余的行
# else:
#     for i in range(5):
#         print(l[(page_num-1)*5 +i].strip())  #输出5行

# 6.如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格
# portfolio = [
#     {'name': 'IBM', 'shares': 100, 'price': 91.1},
#     {'name': 'AAPL', 'shares': 50, 'price': 543.22},
#     {'name': 'FB', 'shares': 200, 'price': 21.09},
#     {'name': 'HPQ', 'shares': 35, 'price': 31.75},
#     {'name': 'YHOO', 'shares': 45, 'price': 16.35},
#     {'name': 'ACME', 'shares': 75, 'price': 115.65}
# ]

# 6.1.计算购买每支股票的总价
# ret = map(lambda dic : {dic['name']:round(dic['shares']*dic['price'],2)},portfolio)
# print(list(ret))

# 6.2.用filter过滤出,单价大于100的股票有哪些
# ret = filter(lambda dic:True if dic['price'] > 100 else False,portfolio)
# print(list(ret))
# ret = filter(lambda dic:dic['price'] > 100,portfolio)
# print(list(ret))
lx
原文地址:https://www.cnblogs.com/bzluren/p/10657220.html