内部列表中的第一项尽可能有效 [英] First items in inner list efficiently as possible
问题描述
我在python A[row,col,value]
中有一个协调的存储列表,用于存储非零值.
I have a coordinated storage list in python A[row,col,value]
for storing non-zeros values.
如何获取所有行索引的列表?我希望此A[0:][0]
可以像print A[0:]
一样打印整个列表,但是print A[0:][0]
仅打印A[0]
.
How can I get the list of all the row indexes? I expected this A[0:][0]
to work as print A[0:]
prints the whole list but print A[0:][0]
only prints A[0]
.
我问的原因是为了有效计算每行 i.e 中的非零值的数量,在range(0,n)
上进行迭代,其中n是总行数.比我目前的for i in range(0,n): for j in A: ...
方法要便宜得多.
The reason I ask is for efficient calculation of the number of non-zero values in each row i.e iterating over range(0,n)
where n is the total number of rows. This should be much cheaper than my current way of 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
吗?
Using Junuxx's answer, this question and this post I came up with the following (for returning the number of singleton rows) which is much faster for my current problems size of A
than my original attempt. However it still grows with the number of rows and columns. I wonder if it's possible to not have to iterate over A
but just upto 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
每个元素的第一个(子)元素.
It's a list comprehension that takes the first (sub-)element of every element of A
.
这篇关于内部列表中的第一项尽可能有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!