可以在循环中加个判断,当是最后一个元素时,不输出最后的逗号就可以了。
修改如下:
参考链接:
n=int(input())
items={}
for i in range(n):
line = input().strip().replace(' ','')
name,price=line.split(',')
if name in items:
items[name]+=float(price)
else:
items[name]=float(price)
# http://c.biancheng.net/view/2239.html
items=sorted(items.items())
i=0 # 使用计数器来判断是否到了列表最后一个元素,初始值赋值为0
print("[",end="")
# https://blog.csdn.net/yaoyuanna/article/details/126009259
for name,price in items:
i=i+1 # 计数器+1,表示当前数据是第几条数据
if i<len(items): # 当不是最后一个元素,则每条数据输出后,再输出一个逗号
print("('{}','${:.2f}')".format(name,price),end=",")
else: # 如果是最后一个元素,则输出此条数据后,不再输出逗号
print("('{}','${:.2f}')".format(name,price),end="")
print("]",end="")