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

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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值