<分区>
我在 python A[row,col,value]
中有一个协调存储列表,用于存储非零值。
如何获取所有行索引的列表?我希望这个 A[0:][0]
可以作为 print A[0:]
打印整个列表,但是 print A[0:][0 ]
只打印 A[0]
。
我问的原因是为了有效计算每行中非零值的数量 i.e 遍历 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 的回答,this question和 this post我想出了以下(用于返回单例行数),对于我当前的 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]