2017-06-17 9 views
1

ここではPython 2.7を使用しています。私は、その成分と指示でランダムなレシピを印刷するプログラムを作成しています。最後にコードを投稿します。私は取得しています出力は次のようになります。ここではformat()を使用して辞書のキーと値をフォーマットする方法

は、レシピ( '寿司'、[ 'マグロ'、 '米'、 'マヨネーズ'、 'わさび'])

  1. ウォッシュオフになっていますマグロ

しかし、私はこれ欲しい:ここ

はレシピです:寿司:マグロ、米、マヨネーズ、わさび

0123マグロ

オフ

  1. ウォッシュは、私はこのような何かを達成するためにフォーマット()メソッドを使用することはできますか?ここで

    は私のコードです:

    import random 
    
    def random_recipe(): 
        recipe_dict = {'ChocolateCake':['flour', 'eggs', 'chocolate', 'oil', 'frosting'], 
            'Pasta':['noodles', 'marinara','onions'], 
            'Sushi':['tuna','rice','mayonnaise','wasabi']} 
    
    
        print "Here is a recipe" + str(random.choice(list(recipe_dict.items()))) 
    
        if recipe_dict.keys() == 'ChocolateCake': 
         print "1. Mix the flour with the eggs" 
        elif recipe_dict.keys() == 'Pasta': 
         print "1. Boil some water" 
        else: 
         print "1. Wash off the tuna" 
    
+0

何かが、これは常に '印刷されるということです1。 'recipe_dict.keys()== ['Pasta'、 'Sushi'、 'C​​hocolateCake']'はレシピに関係なくマグロを洗い流す。 – timotree

+0

ありがとう@timotree – johnnewbie25

答えて

1

あなたがランダムからタプルを取得しているので、あなたがこのコードで期待される出力が得られます以下の作業コード

import random 

recipe_dict = {'ChocolateCake':['flour', 'eggs', 'chocolate', 'oil', 'frosting'], 
       'Pasta':['noodles', 'marinara','onions'], 
       'Sushi':['tuna','rice','mayonnaise','wasabi']} 


ra_item = random.choice(list(recipe_dict.items())) 
print "Here is a recipe {}:{}".format(ra_item[0],','.join(ra_item[1])) 

if recipe_dict.keys() == 'ChocolateCake': 
    print "1. Mix the flour with the eggs" 
elif recipe_dict.keys() == 'Pasta': 
    print "1. Boil some water" 
else: 
    print "1. Wash off the tuna" 

を探します。以下のコードでは、あなたのrecipe_dict

from random import choice 

recipe_dict = {'ChocolateCake':['flour', 'eggs', 'chocolate', 'oil', 'frosting'], 
        'Pasta':['noodles', 'marinara','onions'], 
        'Sushi':['tuna','rice','mayonnaise','wasabi']} 

# Or you can unpack your data: 
# key, val = choice(recipe_dict.items()) 
keys = list(recipe_dict.keys()) 
random_key = choice(keys) 
# Using str.format() 
print "Here is a recipe: {}: {}".format(random_key, ', '.join(recipe_dict[random_key])) 

if random_key == 'ChocolateCake': 
    print "1. Mix the flour with the eggs" 
elif random_key == 'Pasta': 
    print "1. Boil some water" 
else: 
    print "1. Wash off the tuna" 
+0

ありがとうございます。 Pythonで 'join'メソッドは何をしますか? – johnnewbie25

+0

実際には文字列関数です。 iterable(あなたの場合はリスト)内の値を取り、引用符で囲んだ文字と結合します。あなたが答えを受け入れる場合はupvoteを与える:) – Arockia

3

あなたは、この例のように、あなたのdictの値を結合するためにjoin()を使用することができます注意する

for k, v in a.items(): 
    print(k + ': ' + ','.join(map(str, v))) 
0

代替a