【再回首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.pyself_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)
相关文章推荐
- 【再回首Python之美】【重载操作符】实例汇总
- 项目实例汇总
- android用户界面之TabHost教程实例汇总
- android用户界面之GridView教程实例汇总
- Jquery语法实例 汇总
- android用户界面之ScrollView教程实例汇总
- linux awk 内置函数详细介绍(实例)
- android用户界面之Checkbox教程实例汇总
- android用户界面之Gallery教程实例汇总
- Python内置函数的用法实例教程
- Expression Blend实例中文教程系列文章汇总
- android用户界面之ScrollView教程实例汇总
- php常用字符串比较函数实例汇总
- Android使用ZBar扫描二维码/条形码(实例)+常见问题汇总
- android用户界面之PopupWindow教程实例汇总
- java常见事件响应方法实例汇总
- php操作csv文件代码实例汇总
- linux awk 内置函数详细介绍(实例)
- mysql内置函数汇总
- python套接字流重定向实例汇总