Codecademyネット学習Python 6日目
3411 ワード
まず昨日の内容を振り返ってみると、本文の前半は主にfor loopについての内容で、loopはループの意味です.前文にforの一般的な使い方について、for item in list.今回はDictionaryでの使い方に拡張し、for key in d:print d[key]#の各変数を印刷します.次に、for文に条件文を追加する方法について説明します.
「return count」では、正しい値を出力するにはforループから飛び出しなければならないことがC言語からわかります.したがってreturn countはfor文を整列させる必要があります.出力結果は2.それ以外の場合は1.
2つのkeyが同じdictionaryでkeyの情報を同時に出力するには、次の方法を使用します.
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」では、正しい値を出力するにはforループから飛び出しなければならないことがC言語からわかります.したがってreturn countはfor文を整列させる必要があります.出力結果は2.それ以外の場合は1.
2つの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))
。 ~!