for item in numbers:
if condition:
# Do something
在list和function中也能互相嵌套使用,如要计算一个list中有多少相同的item,则要使用计数函数。代码如下:
# Write your function below!
def fizz_count(x):
"""return the count of the string 'fizz'."""
count = 0 #初始化计数
for item in x:
if item == 'fizz':
count += 1
return count
x = ['fizz','buzz','fizz']
print fizz_count(x)
在“return count”中,从C语言中可以知道必须要跳出for循环才能输出正确的值。所以return count必须对齐for语句。输出结果才为2.否则为1.
在两个key相同的dictionary中要想同时输出key的信息可以使用如下方法:
prices = {'banana':4,'apple':2,'orange':1.5,'pear':3}
stock = {'banana':6,'apple':0,'orange':32,'pear':15}
for item in prices:
print item
print 'price: '+ str(prices[item])
print 'stock: '+ str(stock[item])
今天大部分内容都是对昨天的补充和进一步完善。例如list内嵌套Dictionary或者Dictionary内嵌套list。
而且是两者之间的嵌套使用。
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 = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
# Add your function below!
def average(avge):
"""returns the average value of a list."""
return sum(avge)/len(avge)
def get_average(student):
weighted_avge = 0.1*average(student['homework'])+0.3*average(student['quizzes'])+0.6*average(student['tests'])
return weighted_avge
def get_letter_grade(score):
"""return the grade of one's scores."""
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
score = get_average(lloyd)
print get_letter_grade(score)
def get_class_average(students):
"""takes your student to compute the average of your entire class."""
total = 0
for student in students:
total += get_average(student)
return total/len(students)
students = [lloyd,alice,tyler]
print get_class_average(students)
print get_letter_grade(get_class_average(students))
应该多注意在什么时候用引号。什么时候不用~!