python—其他内置函数

1. eval()

将字符串类型的代码执行并返回结果。

eval函数就是实现str与list、dict、tuple之间的转化。

a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
aa = eval(a)
print(type(a))
print(type(aa))
b = "{1: 'a', 2: 'b'}"
bb = eval(b)
print(type(b))
print(type(bb))
c = "([1,2], [3,4], [5,6], [7,8], (9,0))"
cc = eval(c)
print(type(c))
print(type(cc))
d = "3+5"
dd = eval(d)
print(dd)

# 输出结果:
# <class 'str'>
# <class 'list'>
# <class 'str'>
# <class 'dict'>
# <class 'str'>
# <class 'tuple'>

2. exec()

将自字符串类型的代码执行,不返回结果。

print(exec("1+2+3+4"))
#返回None
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)

3. compile

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

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

参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,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')
print(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'
print(name) #执行后name变量有值
#输出:'pythoner'

4. sorted

对List、Dict进行排序,Python提供了两个方法。

用List的成员函数sort进行排序,在本地进行排序,不返回副本。

用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变。

# 列表按照其中每一个值的绝对值排序
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))

5. filter

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

合条件的元素,返回由符合条件元素组成的新list。

# 利用filter()过滤掉偶数

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

list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))

# 输出:[1, 7, 9, 17]
# 删除 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']

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值