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

编程入门 行业动态 更新时间:2024-10-08 10:50:01
本文介绍了内部列表中的第一项尽可能高效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

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

本文发布于:2023-11-29 09:27:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:高效   列表中   第一项

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!