我有这个while循环,我想知道他们是否是一个更加pythonic的方式来编写它:
k = 1
while np.sum(s[0:k]) / s_sum < retained_variance:
k += 1
s
是一个numpy向量。谢谢!
答案 0 :(得分:4)
我会说这是非常pythonic:显性比隐含更好。
答案 1 :(得分:2)
以下代码的最后一行将在一行中找到k
的值:
import numpy as np
import math
s = np.array([1,2,3,4,5,6,7,8,9])
s_sum = 1
retained_variance = 4.3
k = 1
while np.sum(s[0:k]) / s_sum < retained_variance:
k += 1
print (k)
print (np.ceil(np.interp(retained_variance,s.cumsum()/s_sum,range(1,len(s)+1))))
答案 2 :(得分:2)
这更像是Haskell而不是python:
>>> from itertools import count, dropwhile
>>> pred = lambda k: np.sum(s[:k]) / s_sum < retained_variance
>>> head = next # just to look more like haskell
>>> head(dropwhile(pred, count()))
编辑:这会更有效:
>>> from itertools import dropwhile, accumulate
>>> pred = lambda x: x[1] / s_sum < retained_variance
>>> head = next
>>> head(dropwhile(pred, enumerate(accumulate(s), start=1)))[0]
答案 3 :(得分:2)
可能不是最有效的解决方案,但如果需要搜索大部分阵列,则速度很快:
import numpy as np
ss = np.cumsum(s) # array with cumulative sum
k = ss.searchsorted(retained_variance*s_sum) # exploit that ss is monotonically increasing
编辑:西蒙指出
k = np.cumsum(s).searchsorted(retained_variance*s_sum) + 1
是与问题对应的值。