创建一个函数,以出版社名为参数,返回该出版社出版的图书的平均价格
时间: 2023-11-27 17:54:39 浏览: 86
好的,以下是一个示例代码,可以实现这个功能:
```python
def avg_book_price(publisher):
# 假设我们有一个包含图书信息的字典列表
books = [
{"title": "Book 1", "publisher": "Publisher A", "price": 20.0},
{"title": "Book 2", "publisher": "Publisher B", "price": 15.0},
{"title": "Book 3", "publisher": "Publisher A", "price": 25.0},
{"title": "Book 4", "publisher": "Publisher C", "price": 18.0},
{"title": "Book 5", "publisher": "Publisher A", "price": 30.0},
]
# 遍历图书列表,找到所有由该出版社出版的图书并计算平均价格
total_price = 0
count = 0
for book in books:
if book["publisher"] == publisher:
total_price += book["price"]
count += 1
if count == 0:
return None # 如果该出版社没有出版任何图书,则返回空值
avg_price = total_price / count
return avg_price
```
这是一个简单的实现,假设我们有一个包含图书信息的字典列表,遍历该列表并找到所有由指定的出版社出版的图书,然后计算它们的平均价格。如果该出版社没有出版任何图书,则返回空值。你可以将其复制粘贴到 Python 解释器中,然后调用该函数并传入出版社名称,以获得它出版的图书的平均价格。例如:
```python
>>> avg_book_price("Publisher A")
25.0
```