内部列表中的第一项尽可能有效

Chr*_*our 6 python optimization performance list

我在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
Run Code Online (Sandbox Code Playgroud)

过度:

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
Run Code Online (Sandbox Code Playgroud)

编辑:

使用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]
Run Code Online (Sandbox Code Playgroud)

Jun*_*uxx 12

这应该这样做:

c = [x[0] for x in A]
Run Code Online (Sandbox Code Playgroud)

这是一个列表理解,它采用了每个元素的第一个(子)元素A.