1. 题目

[{"name":"zhangsan","price":100.5},
{"name":"zhangsan","price":105.5},
{"name":"zhangsan","price":85.5},
{"name":"zhangsan","price":745},
{"name":"zhangsan","price":102},
{"name":"zhangsan","price":215},
{"name":"lisi","price":253.2},
{"name":"lisi","price":25.8},
{"name":"lisi","price":85},
{"name":"lisi","price":96},
{"name":"lisi","price":79.5},
{"name":"wangwu","price":122.3},
{"name":"wangwu","price":135.5},
{"name":"wangwu","price":122.3}]

(1) 计算每个消费者消费的条数
(2) 计算每个消费者消费的总金额
(3) 计算每个消费者消费的平均金额
(4) 计算所有消费者的总金额
(5) 计算所有消费者的平均金额

 

2. 代码

list = [{"name":"zhangsan","price":100.5},
{"name":"zhangsan","price":105.5},
{"name":"zhangsan","price":85.5},
{"name":"zhangsan","price":745},
{"name":"zhangsan","price":102},
{"name":"zhangsan","price":215},
{"name":"lisi","price":253.2},
{"name":"lisi","price":25.8},
{"name":"lisi","price":85},
{"name":"lisi","price":96},
{"name":"lisi","price":79.5},
{"name":"wangwu","price":122.3},
{"name":"wangwu","price":135.5},
{"name":"wangwu","price":122.3}]

print("-----计算每个消费者消费的条数-----")
a=0     # a 为张三
b=0     # b 为李四
c=0     # c 为王五
for x in list:
    if x["name"] == "zhangsan":
        a+=1
    elif x["name"] == "lisi":
        b+=1
    elif x["name"] == "wangwu":
        c+=1
print("张三消费的条数:" + str(a))
print("李四消费的条数:" + str(b))
print("王五消费的条数:" + str(c))

print("-----计算每个消费者消费的总金额-----")
sum1 = 0
sum2 = 0
sum3 = 0
for x in list:
    if x["name"] == "zhangsan":
        sum1 += x["price"]
    elif x["name"] == "lisi":
        sum2 += x["price"]
    elif x["name"] == "wangwu":
        sum3 += x["price"]
print("张三消费的总金额:" + str(sum1))
print("李四消费的总金额:" + str(sum2))
print("王五消费的总金额:" + str(sum3))

print("-----计算每个消费者消费的平均金额-----")
avg1=0
avg2=0
avg3=0
for x in list:
    if x["name"] == "zhangsan":
        sum1 += x["price"]
        avg1 = sum1/6
    elif x["name"] == "lisi":
        sum2 += x["price"]
        avg2 = sum2/5
    elif x["name"] == "wangwu":
        sum3 += x["price"]
        avg3 = sum3/3
print("张三消费的平均金额:" + str(avg1))
print("李四消费的平均金额:" + str(avg2))
print("王五消费的平均金额:" + str(avg3))

print("-----计算所有消费者消费的总金额-----")
sum = 0
for x in list:
    sum += x["price"]
print("所有消费者的总金额为:" + str(sum))

print("-----计算所有消费者的平均金额-----")
avg = 0
sum = 0
i = 0
for x in list:
    i += 1
    sum += x["price"]
    avg = sum/i
print("所有消费者的平均金额为:" + str(avg))