【问题标题】:How to calculate total expense of common items in a list of tuples in Python? [closed]python - 如何计算Python中元组列表中常见项目的总费用? [关闭]
【发布时间】:2016-03-12 16:36:54
【问题描述】:

从下面的元组列表中,我需要创建一个元组列表:

input=[('bread', '    1.90'), ('bread ', ' 1.95'), ('chips ', '    2.54'), ('milk', '2.35'), ('milk', '2.31'), ('milk  ', '    2.38')]

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

【问题讨论】:

标签: python


【解决方案1】:

一个for 循环和一个列表理解可以做到这一点:

from collections import OrderedDict

dictionary = OrderedDict()
for key, value in input:
    key = key.strip()
    dictionary[key] = dictionary.setdefault(key, 0) + float(value)

out = [(key, "${}".format(value)) for key, value in dictionary.items()]

【讨论】:

  • 非常感谢你,你太棒了!!再次感谢!!
  • 很高兴能帮上忙。如果我的回答解决了您的问题,请考虑点击投票数下方的灰色复选标记接受它。
【解决方案2】:

转到您的元组列表并将它们添加到字典中。之后,您可以创建 t 的结果列表

input = [('bread', '    1.90'), ('bread ', ' 1.95'), ('chips ', '    2.54'), ('milk', '2.35'), ('milk', '2.31'), ('milk  ', '    2.38')]

# Create dictionary from list of tuples
out_dict = {}
for item, value in input:
    item_name = item.rstrip()
    if item_name not in out_dict:
        out_dict[item_name] = float(value)
    else:
        out_dict[item_name] += float(value)

# Create list of tuples from dictionary
out = []
for item in out_dict:
    out.append((item, '${:.2f}'.format(out_dict[item])))

print(out)

打印出来:

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

【讨论】:

  • 完美!!,非常感谢。
【解决方案3】:

可以通过以下代码解决:

def calculate_expenses(filename):
    file_pointer = open(filename, 'r')
    # You can use either .read() or .readline() or .readlines()
    data = file_pointer.readlines()
    # NOW CONTINUE YOUR CODE FROM HERE!!!

    my_dictionary = {}
    for line in data:
        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

【讨论】:

    【解决方案4】:

    这个怎么样:

    >>> l=[('bread', '    1.90'), ('bread ', ' 1.95'), ('chips ', '    2.54'), ('milk', '2.35'), ('milk', '2.31'), ('milk  ', '    2.38')]
    >>>
    >>> from collections import defaultdict
    >>> 
    >>> d = defaultdict(float)
    >>> for k,v in l:
            d[k.strip()] += float(v.strip())
    
    
    >>> d
    defaultdict(<class 'float'>, {'chips': 2.54, 'milk': 7.04, 'bread': 3.8499999999999996})
    >>> out = [(k, '${:.2f}'.format(v)) for k,v in sorted(d.items())]
    >>> out
    [('bread', '$3.85'), ('chips', '$2.54'), ('milk', '$7.04')]
    

    【讨论】:

      【解决方案5】:
      input_data = [("bread", "    1.90"), ("bread", "   1.95"), ("chips", "  2.54"),
                   ("milk", "2.35"), ("milk", "2.31"), ("milk", "  2.38")]
      
      TL = [] # A list
      print(input_data)
      for item, price in input_data:
          if item in TL:
              # converting 'str' values to 'float' and adding them and storing them 
              # back as a 'str' at the same index
              TL[TL.index(item)+1] = str(float(TL[TL.index(item)+1]) + float(price))
          else:
              TL += item, price
      
      input_data = TL
      print(input_data)
      

      【讨论】:

        猜你喜欢
        • 2015-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-07
        • 2019-07-21
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多