我在Python中有一个协调存储列表A[row,col,value]
,用于存储非零值。
如何获取所有行索引的列表?我期望这个A[0:][0]
可以像print A[0:]
一样工作,因为print A[0:]
打印整个列表,但是print A[0:][0]
只打印A[0]
。
我提出这个问题是为了高效计算每行的非零值数量,即迭代range(0,n)
,其中n是总行数。这应该比我的当前方式for i in range(0,n): for j in A: ...
更加便宜。
类似这样:
c = []
# for the total number of rows
for i in range(0,n):
# get number of rows with only one entry in coordinate storage list
if A[0:][0].count(i) == 1: c.append(i)
return c
关于:
c = []
# for the total number of rows
for i in range(0,n):
# get the index and initialize the count to 0
c.append([i,0])
# for every entry in coordinate storage list
for j in A:
# if row index (A[:][0]) is equal to current row i, increment count
if j[0] == i:
c[i][1]+=1
return c
编辑:
根据Junuxx的回答,在这个问题和这篇文章的帮助下,我得到了以下代码(用于返回单行出现的次数),对于我当前A
的问题规模要比我的原始尝试更快。但是它仍然随着行列数的增加而增长。我想知道是否可能不必迭代整个A
而只需迭代到n
?
# get total list of row indexes from coordinate storage list
row_indexes = [i[0] for i in A]
# create dictionary {index:count}
c = Counter(row_indexes)
# return only value where count == 1
return [c[0] for c in c.items() if c[1] == 1]