Top positions in the internal list as efficiently as possible

I have a coordinated storage list in python A[row,col,value] to store values โ€‹โ€‹without zero.

How can I get a list of all row indices? I expected this A[0:][0] work as print A[0:] prints the entire list, but print A[0:][0] prints only A[0] .

The reason I'm asking is to efficiently calculate the number of non-zero values โ€‹โ€‹in each row, iterate over range(0,n) , where n is the total number of rows. This should be much cheaper than my current way for i in range(0,n): for j in A: ...

Sort of:

 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 

EDIT:

Using Junuxx's answer, this question and this post I came up with the following (to return the number of single-line lines), which is much faster for my current problems of size A than my initial attempt. However, it is still growing with the number of rows and columns. I wonder if itโ€™s possible not to iterate over A , but just up to 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] 
+6
source share
2 answers

This should do it:

 c = [x[0] for x in A] 

This is a list comprehension that takes the first (sub) element of each element of A

+10
source

For efficient and extended snippets, you can use numpy , which you think seems like a good idea:

 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 probably better...) count = np.count_nonzero(bc == 1) 
+4
source

All Articles