内置函数

1、内置函数预览

   参考链接:Python3内置函数官方文档

   下表中共列出了Python3目前全部68个内置函数:

 Built-in Functions  
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() 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()

2、内置函数详解

# global 变量
# nonlocal 变量
# locals()    #返回局部作用域中的所有名字
# globals()   #返回全局作用域中的名字

  详解参见大牛博客:https://www.liwenzhou.com/posts/Python/built-in_functions/

3、几个重要的内置函数详解

  3.1  eval、exec、compile

    3.1.1  eval() :把字符串里的字符转换为可执行代码,但只支持一行字符。可以返回执行后得到的值。

f = "3+6+9+8"
s = eval(f)
print(s)

#运行结果:
26

    3.1.2  exec() :把字符串里的字符转换为可执行代码,可以支持多行字符。但是拿不到返回结果。

print(exec("1+2+3+4"))        # None

exec("print('hello,world')")  # hello,world
code = 
'''
def func():
    print('test')
    return 555
func()
'''
 
f = exec(code)
print('---'*5)


#运行结果:
test
---------------
None

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

compile(source, filename, mode[, flags[, dont_inherit]])

    参数说明:   

    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

>>>str = "for i in range(0,10): print(i)" 
>>> c = compile(str,'','exec')   # 编译为字节代码对象 
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
----------------------------------------------------------------------------------------
#简单求值表达式用eval

>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17
----------------------------------------------------------------------------------------
#交互语句用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'"
View Code

  3.2  sorted

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

# sort 与 sorted 区别:

    sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

    list 的 sort 方法返回的是:对已经存在的列表进行操作,而内建函数 sorted 方法返回的是:一个重新排序的 list,而不是在原来的基础上进行的操作
# 语法
sorted(iterable, key=None, reverse=False) 

# iterable -- 可迭代对象。
# key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
# reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
# 列表按照其中每一个值的绝对值排序
l1 = [1,3,5,-2,-4,-6]
l2 = sorted(l1,key=abs,reverse=True)
l1.sort()
print(l1)   # [1, 3, 5, -2, -4, -6]  -->  [-6, -4, -2, 1, 3, 5]
print(l2)   # [-6, 5, -4, 3, -2, 1]


# 列表按照每一个元素的len排序
l = [[1,2],[3,4,5,6],(7,),'123']
print(sorted(l,key=len))          #[(7,), [1, 2], '123', [3, 4, 5, 6]]

 

  3.3  zip、fileter、map

    3.3.1  zip():拉链【可迭代的】

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

l1 = [1,2,3,4,5]
l2 = ['a','b','c','d']
l3 = ('*','**',[1,2])
d = {'k1':1,'k2':2}
for i in zip(l1,l2,l3,d):      # 循环次数:所有对象中最少元素个数
    print(i)

#运行结果:
(1, 'a', '*', 'k1')
(2, 'b', '**', 'k2')
>>> x = ["a", "b", "c"]
>>> y = [1, 2, 3]
>>> a = list(zip(x, y))  # 合包
>>> a
[('a', 1), ('b', 2), ('c', 3)]
>>> b =list(zip(*a))     # 解包
>>> b
[('a', 'b', 'c'), (1, 2, 3)]


# 常见应用:
>>> keys = ["name", "age", "salary"]
>>> values = ["Andy", 18, 50]
>>> d = dict(zip(keys, values))
>>> d
{'name': 'Andy', 'age': 18, 'salary': 50}

    3.3.2  filter

    filter() 函数:用于过滤序列,过滤掉不符合条件的元素。接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

    只管筛选,不会改变原来的值

# 过滤出列表中的所有奇数:

def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)     #[1, 3, 5, 7, 9]

-----------------------------------------------------------------------

# 过滤出1~100中平方根是整数的数:

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
 
newlist = filter(is_sqr, range(1, 101))
print(newlist)     #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    3.3.3 map

    map() :会根据提供的函数对指定序列做映射。

    第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表

    元素个数不变,值可能改变

ret = map(abs,[1,-6,-2,8])
print(list(ret))          #[1, 6, 2, 8]

  3.4  all、any

# all():有一个是false(空)就是false
print(all(['a','',123]))   #False
print(all(['a',123]))      #True
print(all([0,123]))        #False

# any():有一个是True就是True
print(any(['',0,123,'abs']))     #True

  3.5  repr:让一个变量原封不动格式化输出

name = 'egg'
print('你好%s'%name)    # 你好egg
print('你好%r'%name)    # 你好'egg'
print(repr('1'))        # '1'
print(repr(1))          # 1

  扩展: r

# 'r'是防止字符转义的 :
    #如果路径中出现'\t'的话 不加r的话\t就会被转义,而加了'r'之后'\t'就能保留原有的样子
    # 在字符串赋值的时候,前面加'r'可以防止字符串在时候的时候不被转义 原理是在转义字符前加'\'

# 示例:
s=r'\tt'
print(s)
Output:
'\tt'
 
s='\tt'
print(s)
Output:
'        t'

 

posted @ 2019-04-10 12:29  timetellu  阅读(182)  评论(0编辑  收藏  举报