简体   繁体   English

遍历2D数组删除元素,索引错误,Python

[英]Looping through 2d array removing elements, indexing error, python

I am trying to delete empty elements of a list named report info split but keep getting list out of range errors. 我正在尝试删除名为report info split的列表的空元素,但一直使列表超出范围错误。

The list looks similar to this : 该列表看起来类似于:

reportinfosplit = [[1,,g,5,44,f][1,5,4,f,g,,g]]

I have found many answers to this for 1d arrays but not 2d. 我已经找到了许多针对一维数组而不是二维数组的答案。 Is there a way to prevent the index from going out of range? 有没有办法防止索引超出范围? The list elements are not all the same size, and I thought that was the reason, but it kept happening after I made them the same length. 列表元素的大小不尽相同,我认为这是原因,但是在我使它们具有相同的长度之后,这种情况一直在发生。

for i in range(len(reportinfosplit)):
    for j in range(len(reportinfosplit[i])):
        if(j<=len(reportinfosplit[i])):
            if reportinfosplit[i][j] == "":
                del reportinfosplit[i][j]

You can use filter to remove empty values from list 您可以使用filter从列表中删除空值

reportinfosplit = [[1,"","g",5,44,"f"],[1,5,4,"f","g","","g"]]
print([filter(None, i) for i in reportinfosplit])     #Python3 print([list(filter(None, i)) for i in reportinfosplit])

Output: 输出:

[[1, 'g', 5, 44, 'f'], [1, 5, 4, 'f', 'g', 'g']]

Using list comprehensions 使用列表推导

reportinfosplit = [[1,"",'g',5,44,'f'],[1,5,4,'f','g',"",'g']]

for ix, i in enumerate(reportinfosplit):
    reportinfosplit[ix] = [val for val in i if val != '']

print(reportinfosplit)

[[1, 'g', 5, 44, 'f'], [1, 5, 4, 'f', 'g', 'g']] [[1,'g',5,44,'f'],[1,5,4,'f','g','g']]

You are checking j for j<=len(reportinfosplit[i]) , which results in j being able to become as large as the current length of reportinfosplit[i] (which is possible, since the current length of reportinfosplit[i] changes). 您正在检查j是否为j<=len(reportinfosplit[i]) ,这将导致j能够变得与reportinfosplit[i]的当前长度一样大(这是可能的,因为reportinfosplit[i]的当前长度发生了变化)。 Try it like this: 像这样尝试:

for i in range(len(reportinfosplit)):
    for j in range(len(reportinfosplit[i])):
        if(j<len(reportinfosplit[i])):
            if reportinfosplit[i][j] == "":
                del reportinfosplit[i][j]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM