内部列表中的第一项尽可能高效 [英] First items in inner list efficiently as possible

查看:17
本文介绍了内部列表中的第一项尽可能高效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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].

我问的原因是为了有效计算每行中非零值的数量ie迭代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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆