繁体   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