列表排序后列表索引超出范围?

时间:2018-12-05 16:22:49

标签: python csv

def Routine_Maker(number_of_exercises,array):
    routine = []
    i=0
    j=0
    for i in range(number_of_exercises):
        for j in range(2):                
            x = random.randint(0,4)
            movement = array[i][x]
            routine.append(movement)
            j=j+1
        i=i+1
        print (routine)

我的代码搜索了存储在名为array的二维数组中的练习列表,并将它们写入名为routine的数组中

它搜索整个文件并添加所有锻炼,但是最后我得到以下消息。

line 20, in Routine_Maker
    movement = array[i][x]
IndexError: list index out of range

我尝试做for i in range(number_of_exercises-1)以使其与索引保持一致,但这没有用。有任何想法吗?

array如下所示:

[['Bench Press', 'Dumbell Press', 'Chest Press Machine', 'Cable Flies', 'Cable Crossover'], ['Incline Bench Press', 'Incline Dumbell Press', 'Incline Cable Flies', 'Incline Chest Press Machine', 'Incline Dumbell Flies'], ['Barbell Overhead Press', 'Dumbell Overhead Press', 'Dumbell Lateral Raise', 'Face Pulls', 'Dumbell Front Raise'], ['Dumbell Curls ', 'Hammer Curls', 'Preacher Curls', 'Machine Curls', 'Close Grip Chin Ups'], ['Cable Pushdowns', 'Overhead Dumbell Extensions', 'Overhead Barbell Extensions', 'Dips', 'Skullcrushers'], ['Lat Pulldowns', 'Pullups', 'Deadlifts', 'Bent Over Rows', 'Dumbell Rows'], ['Squats', 'Leg Press', 'Calf Raisers', 'Leg Extensions', 'Leg Curls']]

我正在尝试从称为array的数组中的每个数组中随机选择2个练习。例如,第一个数组包括胸部锻炼。下一个数组包括上胸部锻炼,然后是肩部锻炼等。我想从每个数组/肌肉组中随机选择2个。

3 个答案:

答案 0 :(得分:2)

您不需要这些行

i=0
j=0
j=j+1
i=i+1

使用for in循环时。您可以删除它们。

您可能会遇到IndexError,因为number_of_exercises大于len(array)

  

根据您的修改我的猜测

#!/bin/python

array=[['Bench Press', 'Dumbell Press', 'Chest Press Machine', 'Cable Flies', 'Cable Crossover'], ['Incline Bench Press', 'Incline Dumbell Press', 'Incline Cable Flies', 'Incline Chest Press Machine', 'Incline Dumbell Flies'], ['Barbell Overhead Press', 'Dumbell Overhead Press', 'Dumbell Lateral Raise', 'Face Pulls', 'Dumbell Front Raise'], ['Dumbell Curls ', 'Hammer Curls', 'Preacher Curls', 'Machine Curls', 'Close Grip Chin Ups'], ['Cable Pushdowns', 'Overhead Dumbell Extensions', 'Overhead Barbell Extensions', 'Dips', 'Skullcrushers'], ['Lat Pulldowns', 'Pullups', 'Deadlifts', 'Bent Over Rows', 'Dumbell Rows'], ['Squats', 'Leg Press', 'Calf Raisers', 'Leg Extensions', 'Leg Curls']]

import random
def Routine_Maker(array):
    routine = []
    for i in array:
        routine.extend(random.sample(i,2))
    return routine

print(Routine_Maker(array))
# => ['Cable Crossover', 'Bench Press', 'Incline Dumbell Press', 'Incline Dumbell Flies', 'Face Pulls', 'Dumbell Front Raise', 'Preacher Curls', 'Machine Curls', 'Skullcrushers', 'Overhead Dumbell Extensions', 'Deadlifts', 'Pullups', 'Calf Raisers', 'Leg Extensions']

number_of_exercises大于len(array)*2时,您想做什么?

答案 1 :(得分:0)

for循环在每次迭代后已经将1加到变量“ i”和“ j”。因此,不是从0到极限-1,而是从1到极限。只需删除j = j + 1i = i + 1行:)

编辑:

def Routine_Maker(number_of_exercises, array):
    routine = []
    for i in range(number_of_exercises):
        x = random.randint(0, len(array) - 1) 
        y = random.randint(0, 4)
        movement = array[x][y]
        routine.append(movement)
    print (routine)

编辑#2:

这应该按照您所说的做(至少我理解了):)

   def Routine_Maker(number_of_exercises, array):
      routine = []
      pos = 0
      for i in range(number_of_exercises):
            if pos >= len(array):
                pos = 0
            for j in range(2):
                x = random.randint(0,4)
                movement = array[pos][x]
                routine.append(movement)
            pos += 1
      print(routine)

这将返回一个长度为2*number_of_exercises的数组。如果您希望其长度恰好为number_of_exercises,则pos索引应每2次迭代移动一次,只需删除for j语句即可:)

编辑#3:

好吧,我想我明白了

首先,您拥有数据:

array_of_exercises = [['Bench Press', 'Dumbell Press', 'Chest Press Machine', 'Cable Flies', 'Cable Crossover'], 
                      ['Incline Bench Press', 'Incline Dumbell Press', 'Incline Cable Flies', 'Incline Chest Press Machine', 'Incline Dumbell Flies'], 
                      ['Barbell Overhead Press', 'Dumbell Overhead Press', 'Dumbell Lateral Raise', 'Face Pulls', 'Dumbell Front Raise'], 
                      ['Dumbell Curls ', 'Hammer Curls', 'Preacher Curls', 'Machine Curls', 'Close Grip Chin Ups'], 
                      ['Cable Pushdowns', 'Overhead Dumbell Extensions', 'Overhead Barbell Extensions', 'Dips', 'Skullcrushers'],
                      ['Lat Pulldowns', 'Pullups', 'Deadlifts', 'Bent Over Rows', 'Dumbell Rows'], 
                      ['Squats', 'Leg Press', 'Calf Raisers', 'Leg Extensions', 'Leg Curls']]

然后,您说每天要进行多少运动:

exercises_per_day = [2, 4, 3, 1, 3, 5, 3, 2, 3, 4]

这就是函数:

def Routine_Maker(number_of_days, array, exercises_per_day):
    routine = []
    pos = 0
    for i in range(number_of_days):
      if pos >= len(array):
        pos = 0
      temporal_array = [array[pos][j] for j in random.sample(range(5), exercises_per_day[pos])]
      routine.append(temporal_array)
      pos += 1
    print(routine)

所以您这样称呼它:

Routine_Maker(10, array_of_exercises, exercises_per_day) 

这将为您提供类似的信息:

[['Cable Flies', 'Cable Crossover'], 
 ['Incline Dumbell Flies', 'Incline Chest Press Machine', 'Incline Dumbell Press', 'Incline Cable Flies'], 
 ['Dumbell Overhead Press', 'Barbell Overhead Press', 'Dumbell Front Raise'], ['Dumbell Curls '], 
 ['Cable Pushdowns', 'Overhead Dumbell Extensions', 'Dips'], 
 ['Dumbell Rows', 'Bent Over Rows', 'Pullups', 'Lat Pulldowns', 'Deadlifts'], 
 ['Leg Press', 'Squats', 'Leg Curls'], 
 ['Dumbell Press', 'Cable Crossover'], 
 ['Incline Cable Flies', 'Incline Dumbell Flies', 'Incline Dumbell Press', 'Incline Chest Press Machine'], 
 ['Dumbell Lateral Raise', 'Face Pulls', 'Dumbell Front Raise']]

应注意:

  • 如果您说每天要进行的运动比数组中的运动多,这将失败,因为在random.sample中,您不会得到重复,但样本大小必须小于范围。如果需要更多,您将拥有重复项,只需为randomInt对其进行修改即可完成此操作。

  • 当天数大于练习的大小时,它将重新开始(这就是pos的目的。)

答案 2 :(得分:0)

您的问题可能是number_of_exercises大于len(array)。要解决此问题,您需要验证输入,然后根据验证结果执行一些操作。例如,

number_of_exercises = min(number_of_exercises, len(array))

如果大于number_of_exercises,我在这里所做的操作就是将array设置为len(array)的长度,这将使索引错误成为不可能。或者,您可以打印一些警告/错误消息,通知用户他们搞砸了,或同时执行了这两项操作。例如,您可以通过以下方式进行验证:

number_of_exercises = int(input("How many? "))
while ((number_of_exercises < 0) or (number_of_exercises > len(array)):
    print ("Invalid input.")
    try:
        number_of_exercises = int(input(Please provide valid input! "))
    catch ValueError:
        number_of_exercises = -1

此代码禁止用户继续前进,直到他们提供了有效的输入。或者,您可能会显示一条错误消息并退出程序:

import sys

number_of_exercises = int(input("How many? "))
if (number_of_exercises < 0 or number_of_exercises > len(array)):
    print ("Invalid data provided. This program will now exit")
    sys.exit()
相关问题