假如有列表:
```books = [{"name":"C#", "price":23.7, "store":"amaing"},
{"name":"ASP.NET", "price":44.5, "store":"amaing"},
{"name":"C#", "price":24.7, "store":"dd"},
{"name":"ASP.NET", "price":45.7, "store":"dd"},
{"name":"C#", "price":26.7, "store":"xh"},
{"name":"ASP.NET", "price":55.7, "store":"xh"}] _
求:
1、《ASP.NET》价格最便宜的店:
2、求列表中有哪几本书:
3、求每本书的平均价格:
如果有帮助的话,请点击右上角【采纳】按钮,支持一下!!
books = [{"name":"C#", "price":23.7, "store":"amaing"},{"name":"ASP.NET", "price":44.5, "store":"amaing"},{"name":"C#", "price":24.7, "store":"dd"},{"name":"ASP.NET", "price":45.7, "store":"dd"},{"name":"C#", "price":26.7, "store":"xh"},{"name":"ASP.NET", "price":55.7, "store":"xh"}]
# 1、《ASP.NET》价格最便宜的店:
aimbook = "ASP.NET"
price = 100
shopName = [0]
for i in range(len(books)):
if books[i]["name"]==aimbook:
if books[i]["price"] < price:
price = books[i]["price"]
shopName[0] = books[i]["store"]
print("《ASP.NET》价格最便宜的店:",shopName,"价格为:",price)
print()
# 2、求列表中有哪几本书:
bookList = []
for i in range(len(books)):
if books[i]["name"] not in bookList:
bookList.append(books[i]["name"])
print("列表中有:",bookList)
print()
# 3、求每本书的平均价格:
priceList = [0,0]
count = [ 0,0]
for i in range(len(books)):
if books[i]["name"]=="C#":
priceList[0] = priceList[0] + books[i]["price"]
count[0] += 1
elif books[i]["name"]=="ASP.NET":
priceList[1] = priceList[1] + books[i]["price"]
count[1] += 1
print("《C#》的平均价格为:",priceList[0]/count[0])
print("《ASP.NET》的平均价格为:",priceList[1]/count[1])
books = [{"name":"C#", "price":23.7, "store":"amaing"},
{"name":"ASP.NET", "price":44.5, "store":"amaing"},
{"name":"C#", "price":24.7, "store":"dd"},
{"name":"ASP.NET", "price":45.7, "store":"dd"},
{"name":"C#", "price":26.7, "store":"xh"},
{"name":"ASP.NET", "price":55.7, "store":"xh"}]
storename=min([b for b in books if b['name']=="ASP.NET"],key=lambda b:b['price'])["store"]
bookenames=list(set(b['name'] for b in books))
print(storename)
print(bookenames)
你题目的解答代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
books = [{"name":"C#", "price":23.7, "store":"amaing"},
{"name":"ASP.NET", "price":44.5, "store":"amaing"},
{"name":"C#", "price":24.7, "store":"dd"},
{"name":"ASP.NET", "price":45.7, "store":"dd"},
{"name":"C#", "price":26.7, "store":"xh"},
{"name":"ASP.NET", "price":55.7, "store":"xh"}
]
minv = 9999999
d = {}
for v in books:
if v["name"]=="ASP.NET" and v["price"]<minv:
minv = v["price"]
store = v["store"]
t = d.setdefault(v["name"],[0,0])
t[0] += v["price"]
t[1] += 1
print("《ASP.NET》价格最便宜的店是:",store)
print("列表中有哪几本书:",*d)
for k,v in d.items():
print(k,"书的平均价格:",v[0]/v[1])