如果書價超過 800,我需要顯示書名并計算書的平均重量。這是我當前的代碼,感謝任何幫助。非常感謝你!
def calcWeight():
for book in books:
for key,value in book.items():
if key == 'weight':
if value >= 800:
totalWeight = value
avg = totalWeight / 2
print(avg)
books = [{"name": "textbook", "weight": 500, "price": 800},
{"name": "notebook", "weight": 100, "price": 200},
{"name": "storybook", "weight": 700, "price": 1000}]
for book in books:
for key,value in book.items():
if key == 'price':
if value >= 800:
calcWeight()
uj5u.com熱心網友回復:
books = [{"name": "textbook", "weight": 500, "price": 800},
{"name": "notebook", "weight": 100, "price": 200},
{"name": "storybook", "weight": 700, "price": 1000}]
total = 0
length = 0
for book in books:
if book['price'] >= 800:
total = book['weight']
length = 1
average = total / length
print(average)
不過,您不需要回圈輸入字典的鍵。在這里,我假設您的意思是,如果它們的價格大于或等于 800,您將獲得書籍的平均重量
uj5u.com熱心網友回復:
這是您可以做任何事情的一種方法:
def calcWeight(books):
filtered_elements = [book['weight'] for book in books if book['price'] >= 800] # create a list full of weights for those over the price limit
return sum(filtered_elements) / len(filtered_elements) # returns the average of all weighted books
books = [{"name": "textbook", "weight": 500, "price": 800},
{"name": "notebook", "weight": 100, "price": 200},
{"name": "storybook", "weight": 700, "price": 1000}]
average_weight = calcWeight(books) # store the value from the function
for book in books:
if book['price'] >= 800: # grab the value from the dictionary and see if it meets our condition
print(book['name'], average_weight) # print out the name and average
uj5u.com熱心網友回復:
使用 pandas 創建 DataFrame
import pandas as pd
books = [{"name": "textbook", "weight": 500, "price": 800},
{"name": "notebook", "weight": 100, "price": 200},
{"name": "storybook", "weight": 700, "price": 1000},
{"name": "whatever", "weight": 500, "price": 1200}]
df = pd.DataFrame(books)
然后過濾昂貴的書籍:
df_pricy = df[df.price>800]
然后分析資料:
names = list(df_pricy.name)
average_weight = df_pricy.weight.mean()
print("Pricy Books:",names)
print("Average Weight of pricy books",average_weight)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/519795.html
