在二维列表中查找特定列的长度

时间:2018-08-10 16:54:12

标签: python list multidimensional-array multiple-columns content-length

在Python 3中,如果我有一个二维列表,其中最后一行没有完全填写(下面的示例),那么如何获取特定列的长度?

[[1, 2, 3,],
 [4, 5, 6,],
 [7, 8,]]

例如,第0列和第1列的长度为3,但是第2列的长度为2。是否可以在不使用pandas模块的情况下做到这一点?

4 个答案:

答案 0 :(得分:2)

如果某行的索引大于或等于该行的长度,则该列丢失。也就是说,如果一行仅包含2个元素,则存在0列和1列,仅此而已。因此,我们只需要计算长度大于索引的行数即可:

In [58]: L = [[1, 2, 3,], [4,], [7, 8,]]

In [59]: for row in L: print(row)
[1, 2, 3]
[4]
[7, 8]

In [60]: lens = [sum(len(row) > i for row in L) for i in range(max(map(len, L)))]

In [61]: lens
Out[61]: [3, 2, 1]

In [62]: L = [[1, 2, 3,], [4, 5, 6,], [7, 8,]]

In [63]: lens = [sum(len(row) > i for row in L) for i in range(max(map(len, L)))]

In [64]: lens
Out[64]: [3, 3, 2]

max(map(len, L))仅查找列数。如果您只关心查找某一列,则可以执行sum(len(row) > column_number for row in L)

答案 1 :(得分:1)

这是使用itertools.zip_longest的一种方法:

from itertools import zip_longest

lens = [sum(1 for _ in filter(None.__ne__, i)) for i in zip_longest(*L)]

print(lens)

[3, 3, 2]

答案 2 :(得分:1)

由于列表中间不能有空值,所以不完整的列始终是最后一列。不完整的列始终为长度len(lst) - 1,因此您可以使用:

def lenCol(lst, col):
    num_rows = len(lst) # number of rows
    cutoff = len(lst[num_rows-1]) # length of last row, i.e. index where column is 1 shorter
    if col < cutoff:
        return num_rows # if before that index, then just number of rows
    else:
        return num_rows-1 # otherwise number of rows - 1

不需要累加或任何映射功能,因为只有最后一行是不完整的,只需使用列表的属性即可。

如果对您的应用程序尤为重要,那么这还有保持时间恒定的好处。

答案 3 :(得分:0)

这会将您的行值列表更改为列值列表,缺失值用无填充:

list_of_columns = map(list,map(None,*list_of_rows))

然后通过列表理解并过滤出列中的空值,您将获得一个列长列表:

column_lengths = [len(filter(None, col))) for col in list_of_columns]

然后简单地索引(例如lenof列2):

column_lengths[2]
out:
    2