代码之家  ›  专栏  ›  技术社区  ›  user8413109

如何在列表中计算文件中的费用并将其更改为tuple(python)

  •  1
  • user8413109  · 技术社区  · 9 年前

    伙计们,我解决不了这个问题。。。 我有一个文件“text.CSV” 这样地:

    milk,2.35
    bread , 1.95
     chips ,    2.54
    milk  ,    2.38
    milk,2.31
    bread,    1.90
    

    def获取文件,并应返回以下内容:

    [('bread', '$3.85'), ('chips', '$2.54'), ('milk', '$7.04')]
    

    我该怎么做?我试过不同的方法!但我解决不了

    def calculate_expenses(filename):
        file_pointer = open(filename, 'r')
        data = file_pointer.readlines()
        f=[]
        f2=[]
        for i in data:
            x=i.split(',')
            for j in x:
                a=x[0].strip()
                b=x[1].strip()
                a=a.strip('\n')
                b=b.strip('\n')
                b=b.split()
                b.insert(0,'$')
                b="".join(b)
                f.append(a)
                f.append(b)
                f2.append(f)
                f=[]
                break
        return f2
    filename='text.CSV'
    print(calculate_expenses(filename))
    

    [['milk', '$2.35'], ['bread', '$1.95'], ['chips', '$2.54'], ['milk', '$2.38'], ['milk', '$2.31'], ['bread', '$1.90']]
    

    有人能帮我吗?

    3 回复  |  直到 9 年前
        1
  •  1
  •   user8406972 user8406972    9 年前
    def calculate_expenses(filename):
        d= {}
        file_pointer = open(filename, 'r')
        data = file_pointer.readlines()
        for line in data:
            line = line.strip().split(',')
            my_item = line[0].strip()
            my_price = float(line[1].strip())
    
            if my_item not in my_dictionary:
                d[my_item] =  my_price
            else:
                d[my_item] +=  my_price
        l= []
        my_keys = sorted(d.keys())
        for x in my_keys:
            l.append((x,"${0:.2f}".formatd[x])))
        return l
    
        2
  •  0
  •   dashiell    9 年前

    如果你不反对使用熊猫:

    import pandas as pd
    
    df = pd.DataFrame.from_csv('text.csv',index_col=None,header=None)
    df[0] = df[0].apply(lambda x:x.strip())
    df = df.groupby(0).sum().reset_index()
    mylist = zip(df[0],map(lambda x: '${:.2f}'.format(x),df[1]))
    
        3
  •  0
  •   WNG    9 年前

    def calculate_expenses(filename):
        #your dict of results :
        dres={}
        file_pointer = open(filename, 'r')
        data = file_pointer.readlines()
        f=[]
        f2=[]
        for i in data:
            x=i.split(',')
            a=x[0].strip()
            b=x[1].strip()
            a=a.strip('\n')
            b=b.strip('\n')
            if a not in dres:
                dres[a]=0
            dres[a]+=float(b)
            f2=[]
            #outputting the correct format : as an array of tuples
            for k in dres.keys():
                f2+=[(k,'${:.2f}'.format(dres[k]))]
        return f2
    filename='text.CSV'
    print(calculate_expenses(filename))