遍历2d数组时列表索引超出范围

时间:2019-01-04 21:20:32

标签: python arrays

如您所见,以下名为routine的数组内部有一系列其他数组。

[['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

很明显,代码在2d数组中的第一个数组中工作,但是在此之后停止。

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

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']

6 个答案:

答案 0 :(得分:1)

如果您嵌套了list,则可以尝试使用列表理解:

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']

仅当您拥有list的{​​{1}}或两层深度时,此方法才有效。

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

lists

请注意,我已从您的代码中删除了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'] -1range(start, end)start,也就是整个数组,因为数组从end-1开始。也就是说,您不需要0

答案 1 :(得分:0)

您可以尝试以下方法:

for e in routine:
    new_list += e

答案 2 :(得分:0)

这就是您想要的:

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']

答案 3 :(得分:0)

您不需要使用索引。 python可以做到:

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

答案 4 :(得分:0)

使用chain

like

输出

from itertools import chain
a=[['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips'], [], [], [], ['Tricep Kickbacks', 'Overhead Dumbell Extensions'], [], []]
list(chain(*a))

答案 5 :(得分:0)

对于嵌套列表,可以使用chain.from_iterable

来完成将所有组件组合到一个列表中的强大解决方案。
oldlist = [['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips'], [], [], [], ['Tricep Kickbacks', 'Overhead Dumbell Extensions'], [], []]
from itertools import chain
result = list(chain.from_iterable(oldlist))
print(result)
#Output:
['Dumbell Press',
 'Chest Press Machine',
 'Smith Machine Bench Press',
 'Angled Dips',
 'Tricep Kickbacks',
 'Overhead Dumbell Extensions']