【发布时间】:2012-10-16 13:59:25
【问题描述】:
我在 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
结束:
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]
【问题讨论】:
-
@larsman:我假设 A 是三元组列表。
-
你能写一个简单、低效、有效的例子来说明你正在尝试做什么吗?我发现问题的措辞确实令人困惑,而且您的示例代码块似乎都没有做同样的事情..?
-
我正在计算坐标存储列表中仅包含 1 个非零值的所有行。只有第二个代码块略有不同,因为它返回了每一行的计数。我已经用 cmets 更新了代码。
标签: python list optimization performance