通过函数传递数组时,python列表索引超出范围

2024-06-16 11:26:04 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我很难理解这个问题,所以很抱歉在解释时出现任何混乱。你知道吗

我目前正在制作一个健身房锻炼程序生成器,它将随机抽取特定数量(由我指定)的锻炼,用于特定的msucle组(也由我指定)。我有一个名为array的数组,如下所示

[['Bench Press', 'Dumbell Press', 'Chest Press Machine', 'Cable Flies', 'Cable Crossover', 'Decline Bench Press', 'Angled Dips', 'Smith Machine Bench Press', 'Inner Chest Push'], 
['Incline Bench Press', 'Incline Dumbell Press', 'Incline Cable Flies', 'Incline Chest Press Machine', 'Incline Dumbell Flies', 'Raised Pushups', 'Smith Machine Incline Bench Press', 'Rotating Incline Dumbell Press', 'Inner Check Upwards Barbell Push'], 
['Barbell Overhead Press', 'Dumbell Overhead Press', 'Dumbell Lateral Raise', 'Face Pulls', 'Dumbell Front Raise', 'Reverse Flies', 'Smith Shoulder Press', 'Cable Side Raise', 'Behind Head Overhead Press'], 
['Dumbell Curls ', 'Hammer Curls', 'Preacher Curls', 'Machine Curls', 'Close Grip Chin Ups', 'Close Grip Pulldown', 'Half Rep Curls', 'Rotating Curls', 'Drop Set Curls'], 
['Cable Pushdowns', 'Overhead Dumbell Extensions', 'Overhead Barbell Extensions', 'Upright Dips', 'Skullcrushers', 'Close Grip Benchpress', 'Tricep Kickbacks', 'Overhead Rope Extensions', 'Drop Set Pushdowns'], 
['Lat Pulldowns', 'Pullups', 'Deadlifts', 'Bent Over Rows', 'Dumbell Rows', 'Rack Pulls', 'Upright Row', 'Low Rows', 'One Arm Cable Pull'], 
['Squats', 'Leg Press', 'Calf Raisers', 'Leg Extensions', 'Leg Curls', 'Lunges', 'Rear Kicks', 'Abductor', 'Adductor']]

使用2d阵列的每个阵列都包含针对不同肌肉群的练习。你知道吗

现在我创建的程序是4天的程序。第一天,生成胸部和三头肌(数组1和数组5)。第二天是肩膀(阵法3)。第3天是背部和二头肌(阵法4和6),最后第4天是腿部(阵法6)。你知道吗

应使用以下功能设置此系统:

def FourDays():
    global Day1
    Day1 = [4,0,0,0,2,0,0]
    global Day2
    Day2 = [0,0,5,0,0,0,0]
    global Day3
    Day3 = [0,0,0,2,0,4,0]
    global Day4
    Day4 = [0,0,0,0,0,0,5]

    Day1_routine = Routine_Maker3(array, Day1)
    Day2_routine = Routine_Maker3(array, Day2)
    Day3_routine = Routine_Maker3(array, Day3)
    Day4_routine = Routine_Maker3(array, Day4)

例如-Day2(也就是肩部),在数组的第三个索引中有数字5。这意味着第三个阵法有5个练习,这个阵法包含肩部练习。你知道吗

这些变量(Day1Day2Day3Day4)然后被传递给下面的函数,该函数负责从array获得适当的练习量

def Routine_Maker3(array, exercises_per_day):
    old_routine = []
    pos = 0
    for i in range(7):
        if pos >= len(array):
            pos = 0
        temporal_array = [array[pos][j] for j in random.sample(range(9), exercises_per_day[pos])]
        old_routine.append(temporal_array)
        pos += 1
    print (old_routine)

    new_routine=[]
    for e in old_routine:
        new_routine += e
    print (new_routine)

请注意:Day1234应作为exercises_per_day传递

下面是它应该输出的示例:

['Cable Crossover', 'Cable Flies', 'Smith Machine Bench Press', 'Inner Chest Push', 'Upright Dips', 'Overhead Dumbell Extensions']
['Behind Head Overhead Press', 'Dumbell Overhead Press', 'Smith Shoulder Press', 'Face Pulls', 'Dumbell Lateral Raise']
['Machine Curls', 'Close Grip Pulldown', 'Lat Pulldowns', 'One Arm Cable Pull', 'Pullups', 'Upright Row']
['Abductor', 'Rear Kicks', 'Lunges', 'Leg Curls', 'Squats']

我得到的错误是列表索引超出了范围,它说这两行有问题:

Day1_routine = Routine_Maker4(array, Day1)

temporal_array = [array[pos][j] for j in random.sample(range(9), exercises_per_day[pos])]

Tags: posmachinearraypressbenchcableinclineroutine
3条回答

这里有一个更简单的替代方法。你知道吗

def Routine_Maker3(array, exercises_per_day):
    routine = []
    for i in range(7):
        routine.extend(random.sample(array[i], exercises_per_day[i]))
    return routine

Routine_Maker3(array, Day1)

输出:

['Smith Machine Bench Press',
 'Inner Chest Push',
 'Bench Press',
 'Angled Dips',
 'Tricep Kickbacks',
 'Overhead Barbell Extensions']

基本上,random.sample()函数接受一个数组和一个值K,并从数组中返回K个随机值。正是你想要的。你知道吗

您还使用了Routine_Maker4而不是Routine_Maker3。你知道吗

当你试图将一个列表添加到另一个列表时,如果你想要一个平面的1D列表,你需要使用extend()而不是append()

请尝试以下简化代码,以帮助您避免将来出现复杂的错误:

import random

exercises = {"chest": ['Bench Press', 'Dumbell Press', 'Chest Press Machine', 'Cable Flies', 'Cable Crossover', 'Decline Bench Press', 'Angled Dips', 'Smith Machine Bench Press', 'Inner Chest Push'],
             "shoulders": ['Barbell Overhead Press', 'Dumbell Overhead Press', 'Dumbell Lateral Raise', 'Face Pulls', 'Dumbell Front Raise', 'Reverse Flies', 'Smith Shoulder Press', 'Cable Side Raise', 'Behind Head Overhead Press'],
             "back": ['Dumbell Curls ', 'Hammer Curls', 'Preacher Curls', 'Machine Curls', 'Close Grip Chin Ups', 'Close Grip Pulldown', 'Half Rep Curls', 'Rotating Curls', 'Drop Set Curls'],
             "triceps": ['Cable Pushdowns', 'Overhead Dumbell Extensions', 'Overhead Barbell Extensions', 'Upright Dips', 'Skullcrushers', 'Close Grip Benchpress', 'Tricep Kickbacks', 'Overhead Rope Extensions', 'Drop Set Pushdowns'],
             "biceps": ['Lat Pulldowns', 'Pullups', 'Deadlifts', 'Bent Over Rows', 'Dumbell Rows', 'Rack Pulls', 'Upright Row', 'Low Rows', 'One Arm Cable Pull'],
             }


def make_routine(*args, **kwargs):
    routine = []
    muscle_types = list(kwargs.keys())
    for muscle_type in muscle_types:
        muscle_exercises = exercises[muscle_type]
        exercises_per_day = kwargs[muscle_type]
        routine.extend(random.sample(muscle_exercises, exercises_per_day))
    return routine


if __name__ == '__main__':
    day1_routine = make_routine(chest=4, triceps=2)
    day2_routine = make_routine(shoulders=5)
    print("day1_routine:", day1_routine)
    print("day2_routine:", day2_routine)

    # You get the idea
    # Just make you specifications as key word arguments in your calling function
    #

让我们后退几步,对你的问题有一个更长远的看法。你知道吗

您要做的是从列表列表(您称之为数组)中获取具有唯一元素的随机子集。内置的^{} module提供了一个专门的函数来执行这个任务。我说的函数叫做^{}。你知道吗

一般语法(取自文档is):

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. [...]

将此方法应用于您的问题将如下所示:

import random

exercises_0 = ['Bench Press', 'Dumbell Press', 'Chest Press Machine', 'Cable Flies', 'Cable Crossover', 'Decline Bench Press', 'Angled Dips', 'Smith Machine Bench Press', 'Inner Chest Push'] 
exercises_1 = ['Incline Bench Press', 'Incline Dumbell Press', 'Incline Cable Flies', 'Incline Chest Press Machine', 'Incline Dumbell Flies', 'Raised Pushups', 'Smith Machine Incline Bench Press', 'Rotating Incline Dumbell Press', 'Inner Check Upwards Barbell Push']
exercises_2 = ['Barbell Overhead Press', 'Dumbell Overhead Press', 'Dumbell Lateral Raise', 'Face Pulls', 'Dumbell Front Raise', 'Reverse Flies', 'Smith Shoulder Press', 'Cable Side Raise', 'Behind Head Overhead Press']
exercises_3 = ['Dumbell Curls ', 'Hammer Curls', 'Preacher Curls', 'Machine Curls', 'Close Grip Chin Ups', 'Close Grip Pulldown', 'Half Rep Curls', 'Rotating Curls', 'Drop Set Curls']
exercises_4 = ['Cable Pushdowns', 'Overhead Dumbell Extensions', 'Overhead Barbell Extensions', 'Upright Dips', 'Skullcrushers', 'Close Grip Benchpress', 'Tricep Kickbacks', 'Overhead Rope Extensions', 'Drop Set Pushdowns']
exercises_5 = ['Lat Pulldowns', 'Pullups', 'Deadlifts', 'Bent Over Rows', 'Dumbell Rows', 'Rack Pulls', 'Upright Row', 'Low Rows', 'One Arm Cable Pull']
exercises_6 = ['Squats', 'Leg Press', 'Calf Raisers', 'Leg Extensions', 'Leg Curls', 'Lunges', 'Rear Kicks', 'Abductor', 'Adductor']

all_exercises = [exercises_0, exercises_1, exercises_2, exercises_3, exercises_4, exercises_5, exercises_6]

days = [
    [4, 0, 0, 0, 2, 0, 0],
    [0, 0, 5, 0, 0, 0, 0],
    [0, 0, 0, 2, 0, 4, 0],
    [0, 0, 0, 0, 0, 0, 5]
    ]



def get_exercises(day_number):
    output = []
    for idx, value in enumerate(days[day_number]):
        if value:
            # use `append` to get a list of lists
            output.append(random.sample(all_exercises[day_number], value))
            # use `extend` to get a single list
            # output.extend(random.sample(all_exercises[day_number], value))
    return output

exercises_to_do = get_exercises(0)

print(exercises_to_do)

提供以下输出:

[['Dumbell Press', 'Cable Flies', 'Decline Bench Press', 'Cable Crossover'], ['Cable Flies', 'Inner Chest Push']]

相关问题 更多 >