您的位置:首页 > 其它

【再回首Pyhon之美】【内置函数】实例汇总

2018-02-23 17:05 323 查看

Python内置函数示例汇总

每遇到一个新的Python内置函数,追加实例到此。

已汇总内置函数

id(),round(),zip()

id()

id(obj)print "\r\n======id(obj)判断obj是新建的对象还是(被修改)旧的对象==============="
class car(object):
def __init__(self, color):
self.color = color
def setColor(self, color):
self.color = color
obj = car('red') #新建一个对象
print id(obj) #48118976
obj.setColor('black') #只是修改对象
print id(obj) #48118976
obj = car('blue') #新建一个对象
print id(obj) #48119032执行结果:



round()

round(x[,n])print "======round(x[,n])返回浮点数x的四舍五入值======"
print 'round(1.0000):',round(1.0000)
print 'round(1.1111):',round(1.1111)
print 'round(1.5555):',round(1.5555)
print 'round(1.6666):',round(1.6666)

print 'round(1.0006,2):',round(1.0006,2)
print 'round(1.1111,2):',round(1.1111,2)
print 'round(1.5555,2):',round(1.5555,2)
print 'round(1.6666,2):',round(1.6666,2)执行结果:



zip()

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。#ex_python_zip.py
self_file = __file__

#查看zip()返回类型
print 'type(zip()):',type(zip()) #<type 'list'>

#没有参数
ret = zip()
print ret #[]

#只有一个参数
l = [1,2,3] #list
ret = zip(l)
print 'zip([1,2,3]):',zip(l) #[(1,), (2,), (3,)]

#有两个参数且长度相同时
alst = [1,2,3]
blst = [4,5,6]
ret = zip(alst, blst)
print 'zip([1,2,3],[4,5,6]):',ret #[(1, 4), (2, 5), (3, 6)]

#多个参数且长度不同时,以最短的参数的长度为准进行zip
alst = [1,2]
blst = [3,4,5]
clst = [6,7,8,9]
ret = zip(alst,blst,clst)
print 'zip([1,2],[3,4,5],[6,7,8,9]):',ret #[(1, 3, 6), (2, 4, 7)]

#多个参数且长度不同时,以最短的参数的长度为准进行zip
alst = [1,2]
blst = [3,4,5]
name = 'John'
ret = zip(alst, blst, name)
print 'zip([1,2], [3,4,5],\'John\'):',ret #[(1, 3, 'J'), (2, 4, 'o')]

#zip和*操作符可以用来unzip一个列表
ret = [(1, 3, 'J'), (2, 4, 'o')]
(x,y,z) = zip(*ret)
print x #(1, 2)
print y #(3, 4)
print z #('J', 'o')

print 'exit %s' % self_file执行结果



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