函数导入的三种方式
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‘)
#删除数组元素的三个函数
#1. n.pop(index)
#n.pop(index) will remove the item at index from the list and return it to you:
n = [1, 3, 5]
n.pop(1) # Returns 3 (the item at index 1)
print n # prints [1, 5]
#2. n.remove(item) will remove the actual item if it finds it:
n.remove(1) # Removes 1 from the list,NOT the item at index 1
print n # prints [3, 5]
#3. del(n[1]) is like .pop in that it will remove the item at the given index, but it won‘t return it:
del(n[1]) # Doesn‘t return anything
print n # prints [1, 5]
#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
#数组组成的数组
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
#将数组lists中的所有数组的值取出形成一个新的数组
def flatten(lists):
results=[]
for numbers in lists:
for number in numbers:
results.append(number)
return results
print flatten(n)
#数组切割,顺序、倒序
#数组切割的用法相当灵活,基本语法是[start:end:stride],缺省时,start=0,end=len-1,stride#=1。当stride为正时,切割将顺序进行,即从0开始;当stride为负时,切割将逆序进行,即从最后 #一个元素开始。下例中即是从最后一个元素开始每隔一个元素取一个字符
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message=garbled[::-2]
print message 字典
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])
######################################################################################
小练习
######################################################################################
lloyd = { #student lloyd
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = { #student alice
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = { #student tyler
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(numbers): #get the average of a list of numbers
total = float(sum(numbers))
aver = total / len(numbers)
return aver
def get_average(student): #get the average grade of any student
homework = average(student["homework"])
quizze = average(student["quizzes"])
test = average(student["tests"])
return 0.1 * homework + 0.3 * quizze + 0.6 * test
def get_letter_grade(score): #get letter grade,like "A"/"B"/"C"
if(score>=90):
return "A"
elif(score>=80):
return "B"
elif(score>=70):
return "C"
elif(score>=60):
return "D"
else:
return "F"
print get_average(lloyd) #get the average grade of lloyd
#get the average class grade of all students in the class
def get_class_average(students):
results=[]
for student in students :
results.append(get_average(student))
return average(results)
class_average=get_class_average([lloyd,alice,tyler])
print class_average
print get_letter_grade(class_average)
#python内置字典函数
#.items()将分别取出字典的键值对,如(“Monty Python and the Holy Grail”:“Great”)
#.keys()将分别取出字典的键
#.values()将分别取出字典的值
movies = {
"Monty Python and the Holy Grail": "Great",
"Monty Python‘s Life of Brian": "Good",
"Monty Python‘s Meaning of Life": "Okay"
}
print movies.items()range()
#The range function has three different versions: #range(stop) #range(start, stop) #range(start, stop, step) #In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item increases by step. #If omitted, start defaults to zero andstep defaults to one. range(6) # => [0,1,2,3,4,5] range(1,6) # => [1,2,3,4,5] range(1,6,3) # => [1,4]
filter()与lambda函数
#lambda函数与filter()组合非常有用。lambda定义一个匿名函数,下例中x:(x%3==0 or x%5==0)的意#思就是只要x可以被3或5整除,则返回x。而filter函数将num_15中的元素依次取出作为lambda函数的#输入。 num_15=range(1,16) threes_and_fives=filter(lambda x:(x%3==0 or x%5==0),num_15)
本文出自 “DeathlessSun” 博客,请务必保留此出处http://deathlesssun.blog.51cto.com/3343691/1662932
原文:http://deathlesssun.blog.51cto.com/3343691/1662932