Python equivalent of Scala's lazy val -


i'm trying port scala code python project , came across following bit of scala code:

  lazy val numnonzero = weights.filter { case (k,w) => w > 0 }.keys 

weights long list of tuples of items , associated probability weighting. elements added , removed list checking how many elements have non-zero probability relatively rare. there few other rare-but-expensive operations in code i'm porting seem benefit usage of lazy val. idiomatic python way similar scala's lazy val?

generator expression

>>> weights = [(1,2), (2,0), (3, 1)] >>> numnonzero = (k k, w in weights if w > 0) >>> next(numnonzero) 1 >>> next(numnonzero) 3 >>> next(numnonzero) traceback (most recent call last):   file "<stdin>", line 1, in <module> stopiteration >>> next(numnonzero, -1) -1 

>>> numnonzero = (k k, w in weights if w > 0) >>> k in numnonzero: ...     print(k) ...  1 3 

python tutorial: generator expressions


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -