python - 内部列表中的第一项尽可能高效

标签 python list optimization performance

<分区>

我在 python A[row,col,value] 中有一个协调存储列表,用于存储非零值。

如何获取所有行索引的列表?我希望这个 A[0:][0] 可以作为 print A[0:] 打印整个列表,但是 print A[0:][0 ] 只打印 A[0]

我问的原因是为了有效计算每行中非零值的数量 i.e 遍历 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 questionthis 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]

最佳答案

应该这样做:

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

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

关于python - 内部列表中的第一项尽可能高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13084619/

相关文章:

java - Kivy 应用程序崩溃,没有非静态方法 openAPKExpansionInputStream

python - 查找所有不包含某些文本字符串的文本文件

c - 这个数组比较问题的最佳算法是什么?

c - 有L-BFGS-B C端口吗?

python - 删除表达式编辑器中的所有表达式

python - 为什么我在输出文件中看不到实时输出?

python - 如何使用以前训练过的模型来获取图像标签 - TensorFlow

java - 如何在 Java 中保持列表索引固定

c++ - 使用标准列表的内存碎片?

sql - 优化多列 LIKE SQL 查询的一些最佳实践是什么?