【问题标题】:Updating one of several variables depending on user input in python根据 python 中的用户输入更新几个变量之一
【发布时间】:2022-01-07 11:59:30
【问题描述】:

我正在编写我的第一个 Python 项目,除了 CodeWars katas 和我书中的问题练习之外,它旨在计算锻炼计划中每个肌肉群的每周总训练量。

我写的是一本名为bodypart 的大字典,其中key = 锻炼名称(即卧推),value = 主要肌肉群(即胸部)。

然后程序要求用户使用以下代码输入练习和组数:

        # offer option to see valid inputs, then get exercise from user
        print('To see a list of possible exercises, enter "check".')
        exercise = input('What is your first exercise of the day? ')
        if exercise == 'check':
            print(bodypart)
            exercise = input('Please enter an exercise from the list. ')
        while exercise not in bodypart:
            exercise = input('Please enter an exercise from the list. ')
        add_to_part = bodypart.get(exercise)
        print('')

        # get the number of sets and check for valid input
        sets = input('How many sets will you do of this exercise? ')
        if not sets.isdigit:
            sets = input('Please enter a valid number.')
        sets = int(sets)

我为每个主要身体部位创建了一个计数变量,设置为 0。然后我接下来要做的事情似乎很冗长,我觉得必须有一个更优化的方法来做到这一点,但我很困惑如何做。我所做的是根据bodypart 中的值添加相关计数器的组数:

        # add sets to relevant counter
        if add_to_part == 'biceps':
            biceps += sets
        if add_to_part == 'triceps':
            triceps += sets
        if add_to_part == 'chest':
            chest += sets
        if add_to_part == 'shoulders':
            shoulders += sets
        if add_to_part == 'back':
            back += sets
        if add_to_part == 'quads':
            quads += sets
        if add_to_part == 'hams':
            hams += sets
        if add_to_part == 'glutes':
            glutes += sets

在 python 中有没有一种方法可以根据存储在bodypart 中的字符串作为值更新相关变量,而不是为每个单独的肌肉群使用if 语句?

【问题讨论】:

  • 您可以将bodypart 制作成一个字典,其中键是正文部分的名称,值是集合数
  • @Jay 非常感谢!只是为了澄清 - 创建一个新字典或附加 bodypart 八个新键,代表每个主要肌肉群,起始值为 0?
  • 是的,没错,让我添加一些代码
  • @Jay 很有帮助 - 非常感谢您抽出宝贵时间!

标签: python algorithm dictionary if-statement optimization


【解决方案1】:

您可以使用dictionary 来实现您想要的行为

这是一个小代码sn-p -

bodypart_sets = {
    'biceps': 0,
    'triceps': 0,
    'chest': 0,
    'shoulders': 0,
    'back': 0,
    'quads': 0,
    'hams': 0,
    'glutes': 0
}
print(list(bodypart_sets.keys()))

add_to_part = 'chest' # dynamic string
if add_to_part in bodypart_sets:
    bodypart_sets[add_to_part] += 5

print(bodypart_sets['chest'])
print(bodypart_sets)

这个打印 -

['biceps', 'triceps', 'chest', 'shoulders', 'back', 'quads', 'hams', 'glutes']
5
{'biceps': 0, 'triceps': 0, 'chest': 5, 'shoulders': 0, 'back': 0, 'quads': 0, 'hams': 0, 'glutes': 0}

【讨论】:

    猜你喜欢
    • 2015-03-26
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多