2016-03-12 20 views
-2

從元組的文章我需要創建一個元組的列表,使得:如何計算Python中元組列表中常見項目的總費用?

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')] 
+0

命令是否重要? – zondo

+0

是的,排序的名稱和總金額 – user6054437

+0

你有任何的代碼?你有什麼嘗試? – tmthydvnprt

回答

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()] 
+0

非常感謝你,你真棒!再次感謝!! – user6054437

+0

我很高興能幫到你。如果我的答案解決了您的問題,請考慮通過點擊投票計數下面的灰色複選標記來接受它。 – zondo

0

轉到您的元組的列表並將它們添加到字典中。之後,你可以創建你造成

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) 

此打印牛逼名單:

[( '麪包', '$ 3.85'),( '牛奶', '$ 7.04'),('芯片」, '$ 2.54')]

+0

完美!!,非常感謝。 – user6054437

0
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) 
0

如何:

>>> 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')] 
0

它可以通過以下代碼來解決:

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 
相關問題