Python学习笔记之函数
函数导入的三种方式
from math import sqrt """import the sqrt function only""" e.g. sqrt(25) from math import * """import all functions from math module""" e.g. sqrt(25) import math #import math module,and use the function via math.* e.g. math.sqrt(25)
type函数的比较
def distance_from_zero(a): if(type(a)==int or type(a)==float): #the type function return the type of the parameter,and when compare with any type,don‘t round it with quotation mark return abs(a)
list数组
#分割数组 letters = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘] slice = letters[1:3] #slice will get letters[1] and letters[2] ,but no letters[3] print slice print letters #根据指定值获取索引 animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") #在指定索引位置插入值 animals.insert(duck_index,"cobra") #将指定数组值删除.remove backpack = [‘xylophone‘, ‘dagger‘, ‘tent‘, ‘bread loaf‘] backpack.remove(‘dagger‘) #list数组的for循环 start_list = [5, 3, 1, 2, 4] square_list = [] for number in start_list: #依次从start_list取值存入变量number中 square_list.append( number ** 2 ) #对取出的值平方后追加给square_list square_list.sort() #对square_list排序 print square_list
字典
menu = {} # 新建一个空字典 menu[‘Chicken Alfredo‘] = 14.50 #添加键值对 menu[‘Tomato and Eggs‘] = 11 menu[‘Frid Apple‘] = 9.8 menu[‘Tu Dou‘] = 16.5 del menu[‘Frid Apple‘] #删除键值对 menu[‘Tu Dou‘]=10 #修改key对应的值 print "There are " + str(len(menu)) + " items on the menu." #取字典长度len(menu) print menu #字典中的键值对的数据类型可以多种多样 inventory = { ‘gold‘ : 500, ‘pouch‘ : [‘flint‘, ‘twine‘, ‘gemstone‘], # Assigned a new list to ‘pouch‘ key ‘backpack‘ : [‘xylophone‘,‘dagger‘, ‘bedroll‘,‘bread loaf‘] } # Adding a key ‘burlap bag‘ and assigning a list to it inventory[‘burlap bag‘] = [‘apple‘, ‘small ruby‘, ‘three-toed sloth‘] # Sorting the list found under the key ‘pouch‘ inventory[‘pouch‘].sort() # 添加一个键值对,该键值对的值为list inventory[‘pocket‘] = [‘seashell‘,‘strange berry‘,‘lint‘] # 字典中list数组的引用跟数组本身的引用基本没有区别 inventory[‘backpack‘].sort() inventory[‘backpack‘].remove(‘dagger‘) inventory[‘gold‘] = inventory[‘gold‘] + 50 #字典中的for循环,与list一致 webster = { "Aardvark" : "A star of a popular children‘s cartoon show.", "Baa" : "The sound a goat makes.", "Carpet": "Goes on the floor.", "Dab": "A small amount." } # 输出webster中所有key的值 for web in webster: print webster[web] # 字典中for循环的应用实例 prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3} stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15} for key in prices : print key print "price: %s"%(prices[key]) #注意输出字符串的拼接 print "stock: %s"%(stock[key])
本文出自 “DeathlessSun” 博客,请务必保留此出处http://deathlesssun.blog.51cto.com/3343691/1658675
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。