如何压缩我的代码以避免重复for循环?

时间:2019-05-13 00:36:42

标签: python-3.x

我正在尝试提供每周一次的用餐菜单,其中的数据来自两个列表,一个列表用于用餐,另一个列表用于一周中的几天。

我想知道是否可以就重复“ for”循环获得一些建议,因为我相信这样做可能会有更好的方法。

"""Creating Weekly food menu by randomly selecting an item from the 
'meals' list, matching the selected item to a day-of-the-week and
printing out the weekly menu."""

import random

meals = ['Steak', 'Chicken', 'Fish', 'Hamburger', 'Taco', 'HotDog' , 
         'Bier Rocks', 'Pork']

days = ['Monday: ' , 'Tuesday: ' , 'Wednesday: ']

for num in range(1):
    meals_selected = random.choice(meals)
    print(f"The selected meal for {days[0]} {meals_selected}")

for num in range(1):
    meals_selected = random.choice(meals)
    print(f"The selected meal for {days[1]} {meals_selected}")

for num in range(1):
    meals_selected = random.choice(meals)
    print(f"The selected meal for {days[2]} {meals_selected}")

我希望得到类似以下结果:

The selected meal for Monday:  Taco
The selected meal for Tuesday:  Fish
The selected meal for Wednesday:  Hamburger

3 个答案:

答案 0 :(得分:2)

您可以循环播放几天。

import random

meals = ['Steak', 'Chicken', 'Fish', 'Hamburger', 'Taco', 'HotDog' , 'Bier Rocks', 'Pork']

days = ['Monday: ' , 'Tuesday: ' , 'Wednesday: ']

for day in days:
    meals_selected = random.choice(meals)
    print(f"The selected meal for {day} {meals_selected}")

结果:

The selected meal for Monday:  Chicken
The selected meal for Tuesday:  Pork
The selected meal for Wednesday:  HotDog

答案 1 :(得分:2)

如果您要避免在一周内重复同一菜单:

import random

meals = ['Steak', 'Chicken', 'Fish', 'Hamburger', 'Taco', 'HotDog' , 'Bier Rocks', 'Pork']

days = ['Monday' , 'Tuesday' , 'Wednesday']

random.shuffle(meals)
for day, meal in zip (days, meals):
    print(f"The selected meal for {day}: {meal}")

答案 2 :(得分:0)

您可以从使用random.sample开始,这将为您提供3个选择,而无需在一个函数调用中从CharSequence列表中进行替换。

您还可以通过random.shuffle调整就餐清单,以使菜单更加随意

CharSequence

输出将为

meals

只需从import random meals = ['Steak', 'Chicken', 'Fish', 'Hamburger', 'Taco', 'HotDog' , 'Bier Rocks', 'Pork'] days = ['Monday' , 'Tuesday' , 'Wednesday'] #Shuffle the meals random.shuffle(meals) #Choose 3 choices day_meals = random.sample(meals,3) #Print day and respective Choice for idx in range(3): print(f"The selected meal for {days[idx]}: {day_meals[idx]}") 中抽取7个样本,您就可以轻松地扩展此示例以包括所有7天的菜单

The selected meal for Monday: Steak
The selected meal for Tuesday: HotDog
The selected meal for Wednesday: Fish

The selected meal for Monday: Pork
The selected meal for Tuesday: Hamburger
The selected meal for Wednesday: Chicken

......

输出将为

random.sample