有没有办法将2个非常相似的代码片段组合成一个函数并重复?

问题描述 投票:0回答:1

我有两个非常相似的代码片段,我想在代码中放置以防止多次重复自己

这是我的新课程任务,所以我想知道你们是否都知道。我试图在参数中加入一些值,但它不起作用。

pizzaType1 = {
    "Hawaiian":"$8.50", "Pepperoni":"$8.50", "Simply Cheese":"$8.50", "Ham & Cheese":"$8.50", "Beef & Onion":"$8.50", "Cheesy Garlic":"$8.50", "BBQ Pork & Onion":"$8.50"
    }
pizzaType2 = {
    "Mr. Wedge":"$13.50", "Apricot Chicken":"$13.50", "Cranberry & Chicken":"$13.50", "BBQ Meatlovers":"$13.50", "Godfather":"$13.50"
    }

for x,y in pizzaType1.items():
    print(x,y)
for x,y in pizzaType2.items():
    print(x,y)

这是我想在函数中添加的代码

python python-3.x function
1个回答
2
投票

我想这就是你想要的,但我不确定:

pizzaType1 = {
    "Hawaiian":"$8.50", "Pepperoni":"$8.50", "Simply Cheese":"$8.50", "Ham & Cheese":"$8.50", "Beef & Onion":"$8.50", "Cheesy Garlic":"$8.50", "BBQ Pork & Onion":"$8.50"
    }
pizzaType2 = {
    "Mr. Wedge":"$13.50", "Apricot Chicken":"$13.50", "Cranberry & Chicken":"$13.50", "BBQ Meatlovers":"$13.50", "Godfather":"$13.50"
    }

def print_items(dictionary): # make our function
    for x, y in dictionary.items():
        print(x,y)

print_items(pizzaType1) # use our function
print_items(pizzaType2)

输出:

Hawaiian $8.50
Beef & Onion $8.50
Pepperoni $8.50
Simply Cheese $8.50
Cheesy Garlic $8.50
BBQ Pork & Onion $8.50
Ham & Cheese $8.50
Mr. Wedge $13.50
Apricot Chicken $13.50
Godfather $13.50
BBQ Meatlovers $13.50
Cranberry & Chicken $13.50
© www.soinside.com 2019 - 2024. All rights reserved.