Python 遍历二维数组时,列表索引超出范围

Python 遍历二维数组时,列表索引超出范围,python,arrays,Python,Arrays,如您所见,以下名为例程的数组中包含一系列其他数组 [['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips'], [], [], [], ['Tricep Kickbacks', 'Overhead Dumbell Extensions'], [], []] 我已尝试将此数组中的每个项目复制到新数组中。然而,当我这样做时,我得到了这个输出和下面的错误消息 Bench Press Inn

如您所见,以下名为例程的数组中包含一系列其他数组

[['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips'], [], [], [], ['Tricep Kickbacks', 'Overhead Dumbell Extensions'], [], []]
我已尝试将此数组中的每个项目复制到新数组中。然而,当我这样做时,我得到了这个输出和下面的错误消息

Bench Press
Inner Chest Push
Smith Machine Bench Press
Cable Crossover
IndexError: list index out of range
newarray=[]
for x in range(len(routine)-1):
    for i in range(len(routine)-1):
        temp = routine[x][i]
        print (temp)
        newarray.append(temp)
很明显,代码在2d数组中的第一个数组中工作,但是在此之后停止

这是用于生成上述错误消息的代码

Bench Press
Inner Chest Push
Smith Machine Bench Press
Cable Crossover
IndexError: list index out of range
newarray=[]
for x in range(len(routine)-1):
    for i in range(len(routine)-1):
        temp = routine[x][i]
        print (temp)
        newarray.append(temp)
有没有一种方法可以连接这些数组,这样就只有一个数组是这样的

['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips','Tricep Kickbacks', 'Overhead Dumbell Extensions']
如果您有嵌套列表,可以尝试使用列表理解:

routine = [['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips'], [], [], [], ['Tricep Kickbacks', 'Overhead Dumbell Extensions'], [], []]
new_routine = [machine for machines in routine for machine in machines]
print(new_routine)
# ['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips', 'Tricep Kickbacks', 'Overhead Dumbell Extensions']
这只适用于列表列表或两个级别的情况

要更改代码,我们可以执行以下操作以获得相同的结果:

newarray = []
for x in range(len(routine)):
    for i in range(len(routine[x])):
        newarray.append(routine[x][i])

print(newarray)
#['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips', 'Tricep Kickbacks', 'Overhead Dumbell Extensions']
请注意,我从代码中删除了-1。rangestart,end从一个开始到另一个结束-1aka整个数组,因为数组从0开始。也就是说,您不需要-1。您可以尝试以下方法:

for e in routine:
    new_list += e
这就是你想要的:

routine = [['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips'], [], [], [], ['Tricep Kickbacks', 'Overhead Dumbell Extensions'], [], []]


newarray=[]
for i in routine:
        for ii in i:
                newarray.append(ii)

print(newarray) #Output: ['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips', 'Tricep Kickbacks', 'Overhead Dumbell Extensions']

您不需要使用索引。python可以完成以下简单操作:

newlist=[]
for alist in routine:
    for element in alist:
        newlist.append(element)
使用

输出

['Dumbell Press',
 'Chest Press Machine',
 'Smith Machine Bench Press',
 'Angled Dips',
 'Tricep Kickbacks',
 'Overhead Dumbell Extensions']

对于嵌套列表,可以使用


想想莱恩吧。它不会递归到元素中,它只返回外部列表的长度。然而,您将其用于外环和内环。另请参见: