我正在撰寫我的第一個 Python 專案,而不是 CodeWars 卡塔和我書中的問題練習,它旨在計算鍛煉計劃中每個肌肉群的每周總訓練量。
我寫的是一本大字典,叫做bodypartwhere 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為每個單獨的肌肉群使用陳述句?
uj5u.com熱心網友回復:
您可以使用字典來實作您想要的行為
這是一個小代碼片段 -
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}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/408136.html
標籤:
下一篇:條件的PineScript公式?
