【问题标题】:Comparing values in dictionaries in Python and returning a value在 Python 中比较字典中的值并返回一个值
【发布时间】:2016-05-24 11:52:59
【问题描述】:

我在 python 中设置了以下字典。

Ex1={"Upper_body" : True, "Lower_body" : False, "Core" : False,'routine': "4 x 8 reps arm curl, 4 x 8 reps chest press, 4 x 8 reps shoulder press"}
Ex2={"Upper_body" : True, "Lower_body" : False, "Core" : False,'routine':"4 x 8 reps squats, 4 x 8 reps leg press, 20 x lunges"}
Ex3={"Upper_body" : True, "Lower_body" : False, "Core" : True,'routine':"4 x 8 reps arm curl, 4 x 8 reps chest press, 4 x 8 reps shoulder press, 20 min plank"}

我想请客户选择他们想要集中锻炼身体的哪些部位。所以我设置了以下代码来找出客户想要什么:

def yes_no(question):
answer = input(question).lower()
if answer=='yes':
    ans=True
else:
    ans=False
return(ans)

client = { "Upper_body"  : yes_no("Do you want to exercise the upper body? "),
     "Lower_body" : yes_no("Do you want to exercise the lower body? "),
     "Core" : yes_no("Do you want to exercise the core muscle group? ")}

现在我希望程序根据练习字典检查在客户端字典中输入的值,然后从练习中返回/输出与客户端想要的匹配的例程。这个可以吗?

【问题讨论】:

  • 只有这些练习吗?
  • 我希望有更多的练习可能 8 但想知道在我进步之前是否可以做我想做的事情。

标签: python-3.x dictionary compare


【解决方案1】:

我会将每个练习字典放在一个列表中并遍历该列表:

exercises = [
    {"Upper_body" : True, "Lower_body" : False, "Core" : False,'routine': "4 x 8 reps arm curl, 4 x 8 reps chest press, 4 x 8 reps shoulder press"},
    {"Upper_body" : True, "Lower_body" : False, "Core" : False,'routine':"4 x 8 reps squats, 4 x 8 reps leg press, 20 x lunges"},
    {"Upper_body" : True, "Lower_body" : False, "Core" : True,'routine':"4 x 8 reps arm curl, 4 x 8 reps chest press, 4 x 8 reps shoulder press, 20 min plank"}
             ]

def yes_no(question):
    answer = input(question).lower()
    if answer=='yes':
        ans=True
    else:
        ans=False
    return(ans)


client = { "Upper_body"  : yes_no("Do you want to exercise the upper body? "),
     "Lower_body" : yes_no("Do you want to exercise the lower body? "),
     "Core" : yes_no("Do you want to exercise the core muscle group? ")}


for exercise in exercises:
    if exercise["Upper_body"] == client["Upper_body"] and exercise["Lower_body"] == client["Lower_body"] and exercise["Core"] == client["Core"]:
        print(exercise["routine"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多