Codecademy网学习Python第六天

先回顾一下昨天的内容,本文前半部分主要是关于for loop的内容,loop是循环的意思。前文有关于for的一般用法,for item in list. 本次将其拓展为在Dictionary里的用法,为for key in d: print d[key] #打印每一个变量。接下来是关于在for语句中加入条件语句的方法如下:
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])


当然在print 中也能使用%.1f等,但由于有些数据没有小数,所以这样就不是输出原有数据了!

今天大部分内容都是对昨天的补充和进一步完善。例如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))
    
应该多注意在什么时候用引号。什么时候不用~!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值