我在python A[row,col,value]
中有一个协调的存储列表,用于存储非零件值。
如何获取所有行索引的列表?我希望此A[0:][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
Over:
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]
这应该做到:
c = [x[0] for x in A]
这是一个列表理解,它是A
的每个元素的第一个(子)元素。
对于效率和扩展切片,您可以使用numpy
-给定示例似乎是一个好主意:
import numpy as np
yourlist = [
[0, 0, 0],
[0, 1, 1],
[1, 0, 2]
]
a = np.array(yourlist)
print a[:,0]
# [0 0 1]
bc = np.bincount(a[:,0])
# array([2, 1])
count = bc[bc==1].size
# 1
# or... (I think it's probably better...)
count = np.count_nonzero(bc == 1)