返回一个行列表作为元组列表,并使用$格式化值

时间:2016-03-07 10:59:28

标签: list python-3.x tuples

def format_Dollar_sign(list):

    lines=['book, 400.2\n', 'pen, 5\n', 'food,  200.5\n', 'gas, 20\n', 'food, 100\n', 'pen, 10\n', 'insurance, 171.35\n', 'gas, 35\n', 'book, 100\n', 'pen, 12\n', 'food, 320\n', 'gas,23.55\n', 'insurance, 110.25']

    #t=[]
    l1 = []
    l2 = []
    for line in lines:
        #l=[]
        parline =line[:-1]
        l1.append(parline)
        t = tuple(l1)
        l2.append(t)

        l1=[]
    L='[' + ', '.join('({})'.format(t[0]) for t in sorted(l2)) + ']'
    return L

print(format_Dollar_sign(list))

此代码为我输出: [(书,100),(书,400.2),(食物,200.5)......]

但我看输出为: [(' book',' $ 500.20'),(' food',' $ 200.50')...]

值是以$开头的字符串,它们在小数点后有两位精度。此外,项目名称已排序。

有人可以提出解决这个问题的方法。

2 个答案:

答案 0 :(得分:1)

我按如下方式解决了这个问题:

def format_Dollar_sign(list):

    lines=['book, 400.2\n', 'pen, 5\n', 'food,  200.5\n', 'gas, 20\n', 
            'food, 100\n', 'pen, 10\n', 'insurance, 171.35\n', 'gas, 35\n', 
            'book, 100\n', 'pen, 12\n', 'food, 320\n', 
            'gas,23.55\n', 'insurance, 110.25']

    my_dictionary = {}
    for line in lines:
        item, price= line.strip().split(',')

        my_dictionary[item.strip()] = my_dictionary.get(item.strip(),0) + float(price)

    dic={}
    for k,v in my_dictionary.items():
        dic[k]='${0:.2f}'.format(round(v,2))

    L=([(k,v) for k, v in dic.iteritems()])
    L.sort()

    return L
print(format_Dollar_sign(list))

答案 1 :(得分:0)

标准库中的locale模块很好地处理了这个问题。这是一种方法,它可以提供您想要的输出:

import locale


locale.setlocale(locale.LC_ALL, '')
lines=['book, 400.2\n', 'pen, 5\n', 'food,  200.5\n', 'gas, 20\n',
       'food, 100\n', 'pen, 10\n', 'insurance, 171.35\n', 'gas, 35\n',
       'book, 100\n', 'pen, 12\n', 'food, 320\n', 'gas,23.55\n',
       'insurance, 110.25']
itemTupleList = []

for i in lines:
    item = i.split(',')[0]

    # Here I am selecting price, ignoring new line characters, 
    # stripping leading/trailing spaces, converting string to float
    # and finally formatting.
    price = locale.currency(float(i.split(',')[1][:-1].strip()))

    itemTupleList.append((item, price))

print(sorted(itemTupleList))

此问题中讨论了此格式和其他货币格式解决方案:Currency formatting in Python