簡體   English   中英

從兩個列表中制作字典,從第一個列表中獲取 01 變量,從另一個列表中獲取 n(用戶定義)變量

[英]Making a dictionary out of two lists taking 01 variable from 1st list and n (user defined) variable from the other

請注意,我正在嘗試制作一個程序,該程序從用戶那里獲取比薩餅和澆頭的輸入,並使用用戶輸入制作兩個列表(比薩餅和澆頭)。 但是我想使用兩個列表{第一個列表的元素:[對(或n)中的值]}制作一個字典。

請在下面找到我的程序代碼供您參考。

# List in Dictionary
# Making a list and dictionary with user inputs

p = int (input ("Enter the no. of pizzas you want to buy (max 3): "))
t = int (input ("Enter the toppings you would like in each pizza (max 4): "))
b = 1
pizzas = []
toppings = []
for pizza in range(p):
    pizza = ""
    pizza = str(input(f"\nEnter the flavor of Pizza No. {b}: "))
    pizzas.append (pizza)
    b += 1
    c = 1
    for topping in range(t):    
        topping = str(input(f"Enter the flavor of Topping No. {c}: "))
        toppings.append (topping)
        c += 1
print ()
print (pizzas)
print (toppings)

當前 OUTPUT

Enter the no. of pizzas you want to buy (max 3): 2
Enter the toppings you would like in each pizza (max 4): 2

Enter the flavor of Pizza No. 1: Chicken Tikka
Enter the flavor of Topping No. 1: Cheese
Enter the flavor of Topping No. 2: Tikka

Enter the flavor of Pizza No. 2: Veggie Pizza
Enter the flavor of Topping No. 1: Olives
Enter the flavor of Topping No. 2: Mushrooms

['Chicken Tikka', 'Veggie Pizza']
['Cheese', 'Tikka', 'Olives', 'Mushrooms']

需要 OUTPUT

Enter the no. of pizzas you want to buy (max 3): 2
Enter the toppings you would like in each pizza (max 4): 2

Enter the flavor of Pizza No. 1: Chicken Tikka
Enter the flavor of Topping No. 1: Cheese
Enter the flavor of Topping No. 2: Tikka

Enter the flavor of Pizza No. 2: Veggie Pizza
Enter the flavor of Topping No. 1: Olives
Enter the flavor of Topping No. 2: Mushrooms

['Chicken Tikka', 'Veggie Pizza']
['Cheese', 'Tikka', 'Olives', 'Mushrooms']

Dict_pizza = {'Chicken Tikka':['Cheese','Tikka'], 'Veggie Pizza':['Olives', 'Mushrooms']} 

嘗試將 dict_pizza 與輸入變量等同(沒有用),也試過 dict.fromkeys (也沒有用),我的 output 出來了

Dict_pizza = {'Veggie Pizza':['Cheese','Tikka','Olives', 'Mushrooms']}

最后說明:剛開始學習 python 03 周前,所以對這門語言和這個論壇有點新手。 預先感謝您的支持和幫助。

您可以制作帶有澆頭listdict

dict_pizza = {}
for _ in range(p):
    pizza = ""
    pizza = str(input(f"\nEnter the flavor of Pizza No. {b}: "))
    dict_pizza[pizza] = []
    b += 1
    c = 1
    for _ in range(t):    
        topping = str(input(f"Enter the flavor of Topping No. {c}: "))
        dict_pizza[pizza].append(topping)
        c += 1

然后, dict_pizza將擁有 output 如您所說。 比薩的名稱只會在dict_pizza.keys()中,每個特定比薩的頂部可以通過dict_pizza["pizza name"]訪問。

不過,我會多清理一下您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM