是否有更多的pythonic方法来编写只更新变量的while循环?

前端之家收集整理的这篇文章主要介绍了是否有更多的pythonic方法来编写只更新变量的while循环?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个while循环,我想知道它们是否是一种更加 pythonic的方式来编写它:
  1. k = 1
  2. while np.sum(s[0:k]) / s_sum < retained_variance:
  3. k += 1

s是一个numpy向量.谢谢!

解决方法

可能不是最有效的解决方案,但如果需要搜索大多数阵列,则速度很快:
  1. import numpy as np
  2.  
  3. ss = np.cumsum(s) # array with cumulative sum
  4. k = ss.searchsorted(retained_variance*s_sum) # exploit that ss is monotonically increasing

编辑:西蒙指出

  1. k = np.cumsum(s).searchsorted(retained_variance*s_sum) + 1

是与问题对应的值.

猜你在找的Python相关文章