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

2024-04-26 18:59:58 发布

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

如您所见,以下名为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']

Tags: range数组machinetemppresssmithbenchchest
3条回答

这就是你想要的:

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

你可以试试这个:

for e in routine:
    new_list += e

如果有嵌套的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']

只有当你有listlists或两个级别的深度时,这才有效。你知道吗

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

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)startend-1也就是整个数组,因为数组从0开始。也就是说,你不需要-1。你知道吗

相关问题 更多 >