【问题标题】:Return a list of lines as list of tuple with formatting the value with $将行列表作为元组列表返回,并使用 $ 格式化值
【发布时间】:2016-03-07 10:59:27
【问题描述】:
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))

这段代码给我的输出是: [(book,100),(book,400.2),(food, 200.5)...]

但我正在寻找输出: [('book','$500.20'),('food', '$200.50')...]

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

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

【问题讨论】:

    标签: list python-3.x tuples


    【解决方案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))
    

    【讨论】:

    • 我必须等待 18 小时,因为这是我自己的答案。
    【解决方案2】:

    标准库中的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

    【讨论】:

    • 感谢您的代码。您使用语言环境,但可以通过使用 "${:.2f}" 格式化来正确创建和格式化总费用的字符串来解决。此外,您的代码不止一次返回相同的项目。这里需要将所有值添加到同一个项目,例如('book':'$500.20') 而不是 ('book':'$400.20'), ('book':'$100')。因此,这应该返回每个元组包含项目的名称和该项目的总费用。希望这会澄清。
    • 您问题中所需的输出将 book 显示为一个元组两次。你需要更新它。听起来您已经有了解决方案。将来请确保您的问题和期望的输出准确无误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多