假如有列表:
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 求列表中有那几本书: 4 列表里的书都打5折: 5 《C#》的平均价格: 6 求每本书的平均价格:
1. min=0 for i in books: if(i['name']=='ASP.NET'): if min<i['price']: #global min,ri min=i['price'] ri=i; print ri 2. price=0 for b in books: if(b['store']=='xh'): price+=b['price'] print price 3. bname =[] for b in books: bname.append(b['name']) ##不能用bname+= bname=list(set(bname)) print bname 4. books2=[] price=0 bookNum=0 for b in books: b['price']=b['price']/2 books2.append(b) print books2 5. price=0 bookNum=0 for b in books: if(b['name']=='C#'): price+=b['price'] bookNum=bookNum+1 print price*1.0/bookNum 6. nameNum={} namePrice={} books2=list(set()) str='' for a in books: if a['name'] in nameNum: str=a['name'] nameNum[str]=nameNum[str]+1 namePrice[str]=namePrice[str]+a['price'] else: str=a['name'] nameNum[str]=1 namePrice[str]=a['price'] print nameNum print namePrice nameAvg={} for a in nameNum: str=a temp=namePrice[str]*1.0/nameNum[str] nameAvg[str]=temp print nameAvg