python - 是否可以将范围作为变量 "var = k:k+number"

标签 python python-2.7 numpy

我的循环方程式很长。在将其代入方程行之前,我想明确定义一个范围。

这是我的循环。 k 表示我想在等式中使用的范围

    k = 0
    char_num = np.array([196, 191, 122])

    for p in xrange(3):
        # k = "k:(char_num[p]+ k)" # here is the range I which to use

        ## below is the equation which is quite cluttering. 
        H[k,:] = (H[k,:]/(2)) * \
                    (( np.sqrt((sum(W[:,k]))**2 + \
                    (4*sum((V[:,:].T*W[:,k]).T/np.dot(W[:,:],H[:,:]))) )))


        # k += char_num[p]

是否可以将 k 定义为伪代码所示的范围?

最佳答案

我们可以在 char_num 上使用 cumsum 生成这些开始、停止索引,然后在循环中使用它们来切片 H,就像这样 -

s = np.r_[0,char_num.cumsum()]
for i,j in zip(s[:-1], s[1:]): 
    H[i:j,:] = ...

sample 运行-

In [18]: char_num = np.array([196, 191, 122])

In [19]: s = np.r_[0,char_num.cumsum()]
    ...: for i,j in zip(s[:-1], s[1:]): 
    ...:     print(i,j) # print start, stop indices
    ...:     
(0, 196)
(196, 387)
(387, 509)

如果您确实需要将范围作为数组用于除切片之外的某些处理,我们可以使用 range(i,j)np.arange(i,j) 在循环中。我们也可以使用该范围进行切片,但这会强制复制并且会减慢速度。

或者,我们可以在那里使用切片符号,就像这样 -

slice0 = slice(i,j)
H[slice0] = ... # equivalent to H[i:j], i.e. H[i:j,:]

关于python - 是否可以将范围作为变量 "var = k:k+number",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45903786/

相关文章:

python - 比丘达; nvcc 致命 : Visual Studio configuration file '(null)' could not be found

python - While 循环打印列表格式

python - pandas/numpy int64 中意外的 32 位整数溢出(python 3.6)

python - 求解线性方程组和线性不等式

python - 对于相同的操作数,按位左移不同的结果

python - 具有 11 到 20 位数字的随机数

python - 识别无人机图像中的汽车

python - 字典可以用作 matplotlib.pyplot 的完整输入吗?

Python - 从主文件运行多个Python脚本

python - 在安装时检测 Python 传递依赖问题?