您的位置:首页 > 编程语言 > Python开发

Python3.5常见内置方法参数用法实例详解

2019-04-29 18:01 1161 查看

本文实例讲述了Python3.5常见内置方法参数用法。分享给大家供大家参考,具体如下:

Python的内置方法参数详解网站为:https://docs.python.org/3/library/functions.html?highlight=built#ascii

1、abs(x):返回一个数字的绝对值。参数可以是整数或浮点数。如果参数是一个复数,则返回它的大小。

#内置函数abs()
print(abs(-2))
print(abs(4.5))
print(abs(0.1+7j))

运行结果:

2
4.5
7.000714249274855

2、all(Iterable):如果可迭代的对象的元素全部为真(即:非零)或可迭代对象为空,返回True,否则返回False

#内置函数all()
print(all([-1,0,7.5]))
print(all([9,-1.6,12]))
print(all([]))

运行结果:

False
True
True

3、any(Iterable):如果可迭代的对象的元素中有一个为真(即:非零),返回True,可迭代对象的元素全部为零(全部为假)或者可迭代对象为空时则返回False。

#内置函数any()
print(any([-1,0,7.5]))
print(any([0,0,0]))
print(any([]))

运行结果:

True
False
False

4、ascii(object):将内存对象变成可打印的字符串的形式。

#内置函数ascii(object)
a = ascii([1,2,'你好'])
print(type(a),[a])

运行结果:

<class 'str'> ["[1, 2, '\\u4f60\\u597d']"]

5、bin(x):将十进制整数转换成二进制

#内置函数bin()
print(bin(0))
print(bin(2))
print(bin(8))
print(bin(255))

运行结果:

0b0
0b10
0b1000
0b11111111

6、bool([x]):返回一个bool值,0:返回False,非0:返回True;空列表:返回False

#内置函数bool()
print(bool(0))
print(bool(1))
print(bool([]))
print(bool([3]))

运行结果:

False
True
False
True

7、bytearray():返回一个新的字节数组,可修改的二进制字节格式。

#内置函数bytearray()
a = bytes("abcde",encoding='utf-8')
print(a)

b = bytearray("abcde",encoding='utf-8')
print(b)
b[1] = 100
print(b)

运行结果:

b'abcde'
bytearray(b'abcde')
bytearray(b'adcde')

8、callable(object):判断是否可调用(函数和类可以调用),列表等不可调用

#内置函数callable
def nice():
pass
print(callable(nice))
print(callable([]))

运行结果:

True
False

9、chr(i):返回数字对应的ASCII码对应表;相反地,ord():返回ASCII码对应的数字

#内置函数chr()与ord()
print(chr(98))
print(ord('c'))

运行结果:

b
99

10、compile():将字符串编译成可执行的代码

#内置函数compile
code = "for i in range(10):print(i)"
print(compile(code,'','exec'))
exec(code)

运行结果:

<code object <module> at 0x008BF700, file "", line 1>
0
1
2
3
4
5
6
7
8
9

11、dir():可以查方法

#内置函数dir
s = []
print(dir(s))

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__','__mul__', '__ne__', '__new__',
 '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

12、divmod(a,b):返回商和余数

#内置函数divmod()
print(divmod(5,3))
print(divmod(8,9))

运行结果:

(1, 2)
(0, 8)

13、enumerate():是枚举、列举的意思。
对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,

利用它可以同时获得索引和值;enumerate多用于在for循环中得到计数。

#内置函数enumerate
list = ['欢','迎','你']
for index,item in enumerate(list):
print(index,item)

运行结果:

0 欢
1 迎
2 你

13、eval():将字符串str当成有效的表达式来求值并返回计算结果。

#内置函数eval()
#字符串转换成列表
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
print(type(a))
b = eval(a)
print(b)
print(type(b))
#字符串转换成字典
a = "{1: 'a', 2: 'b'}"
print(type(a))
b = eval(a)
print(b)
print(type(b))
#字符串转换成元组
a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
print(type(a))
b = eval(a)
print(b)
print(type(b))

运行结果:

<class 'str'>
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
<class 'list'>
<class 'str'>
{1: 'a', 2: 'b'}
<class 'dict'>
<class 'str'>
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
<class 'tuple'>

14、filter(function,iterable):过滤序列。

匿名函数用完释放,不重复使用。

#匿名函数
calc = lambda n:print(n)
calc(3)
res = filter(lambda n:n>5,range(10))
for i in res:
print(i)

运行结果:

3
6
7
8
9

15、map():可以把一个 list 转换为另一个 list,只需要传入转换函数.

res = map(lambda n:n*n,range(5))  #等价于列表生成式[lambda i:i*i for i in range(5)]
for i in res:
print(i)

运行结果:

0
1
4
9
16

16、reduce():python 3.0.0.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.

它可以通过传给reduce中的函数(必须是二元函数)依次对数据集中的数据进行操作。

凡是要对一个集合进行操作的,并且要有一个统计结果的,能够用循环或者递归方式解决的问题,一般情况下都可以用reduce方式实现。

from functools import reduce
res = reduce(lambda x,y:x+y,range(10))  #求和
res1 = reduce(lambda x,y:x*y,range(1,10)) #阶乘
print(res)
print(res1)

运行结果:

45
362880

17、globals():返回的是全局变量的字典,修改其中的内容,值会真正的发生改变。
locals():会以dict类型返回当前位置的全部局部变量。

def test():
loc_var = 234
print(locals())
test()

运行结果:

{'loc_var': 234}

18、hash():函数返回对象的哈希值。返回的哈希值是使用一个整数表示,通常使用在字典里,以便实现快速查询键值。

print(hash('liu'))
print(hash("liu"))
print(hash('al'))
print(hash(3))

运行结果:

-1221260751
-1221260751
993930640
3

19、hex(x):将一个数字转换成十六进制

oct(x):将一个数字转换成八进制

print(hex(15))
print(hex(32))

运行结果:

0xf
0x20

print(oct(8))
print(oct(16))
print(oct(31))

运行结果:

0o10
0o20
0o37

20、round():返回浮点数x的四舍五入值

print(round(1.3457,3))

运行结果:

1.346

21、sorted():排序

a = {6:2,8:0,1:4,-5:6,99:11,4:22}
print(sorted(a.items())) #按照键排序
print(sorted(a.items(),key=lambda x:x[1]))  #按照键值排序

运行结果:

[(-5, 6), (1, 4), (4, 22), (6, 2), (8, 0), (99, 11)]
[(8, 0), (6, 2), (1, 4), (-5, 6), (99, 11), (4, 22)]

22、zip():接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。

a = [1,2,3,4]
b = ['a','b','c','d']
for i in zip(a,b):
print(i)

运行结果:

(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')

23、__import__('decorator')等价于import decorator

关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: