2016-11-29 10 views
0
def get_quantities(table_to_foods): 
    """ (dict of {str: list of str}) -> dict of {str: int} 

    The table_to_foods dict has table names as keys (e.g., 't1', 't2', 
    and so on) and each value is a list of foods ordered for that table. 

    Return a dictionary where each key is a food from table_to_foods and 
    each value is the quantity of that food that was ordered. 

    >>> get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']}) 
    {'Vegetarian stew': 3, 'Poutine': 2, 'Steak pie': 3}  
    """ 

    food_to_quantity = {} 

    # Accumulate the food information here. 

    return food_to_quantity 

私は何もインポートできません(コレクション/チェーン)。私は以下で試した2つの選択肢がありますが、どちらも失敗しました。Python:各キーが食べ物であり、各値が注文された食べ物の量である辞書を返す方法?

これは、プログラムの時間を作る:

for table in table_to_foods: 
    count = 0 
    while count < len(table): 
     for food in table[count]: 
      if food in food_to_quantity: 
       food_to_quantity[food] += 1 
      else: 
       food_to_quantity[food] = 1 
    count += 1 

これははAttributeErrorを取得します。

for table_order in table_to_foods.itervalues(): 
    for menu_item in table_order: 
     if menu_item in food_to_quantity: 
      food_to_quantity[menu_item] += 1 
     else: 
      food_to_quantity[menu_item] = 1 

答えて

1

あなたは本当に接近していました。あなたの第二のスニペットは:

for table_order in table_to_foods.itervalues(): 
    for menu_item in table_order: 
     if menu_item in food_to_quantity: 
      food_to_quantity[menu_item] += 1 
     else: 
      food_to_quantity[menu_item] = 1 

古いPythonの2 itervalues方法を使用しているが、あなたは、Python 3にあなたは、Python 2.7 viewvalues方法と同じですvaluesを、使用する必要があります。これを変更すると、このスニペットが機能するはずです。

最初のスニペットにはさらに問題があります。たとえば、len(table)は、テーブル名の文字数であり、興味のあるものではありません。不明な役割を持つ3つのループを使用しようとしました。 countを使用するループの外側にcount += 1も配置しました。

+0

はどうもありがとうございます動作します!私はitervaluesを値に変更すると、これは完璧に機能しました:)私はあなたが私に事を説明する時間を費やしてくれて、私は十分な評判を持っていないために表示されませんが、あなたをアップしました – Ama

1

これは

def get_quantities(table_to_foods): 
    ''' 
    Takes a dictionary containing a list of strings and returns the 
    string and count 

    get_quantities(dict(str:[str])) -> dict(str:int) 
    ''' 

    result = {} 

    for table in table_to_foods: 
     for item in table_to_foods[table]: 
      result[item] = result.get(item, 0) + 1 
    return result 
+0

'item_list 'の場合、' item_list:if item in list: 'を' if item in result: 'に置き換えることができます。これら以外の辞書方法を使用することが許可されていない場合は、これが最善の方法です。内部ループ本体は 'get'メソッドを使用して1行に書くことができます:' result [item] = result.get(item、0)+ 1' –

+0

これはコーディングシステムでは機能しませんでした(残念ながら)それは私が持っていた以上のものです。私は「正式に」あなたをアップアップするのに十分な評判を持っていませんが、これを見てアドバイス/フィードバックを提供する時間を本当に感謝しています。 – Ama

関連する問題