【问题标题】:Python - attribute specific values with imbricated loopsPython - 具有重叠循环的属性特定值
【发布时间】:2015-04-23 21:59:49
【问题描述】:

我在使用叠瓦式循环存储值时遇到了一些问题... 这是一个与我的案例很接近的例子。 为了限制代码的大小,我添加了“a”作为随机值。

对于每个“图像”,我必须计算 dX,如果我能达到我的标准,我会输入一个特定的值 (100),然后我会打破循环进入下一张图像!如果我无法在迭代最大值之前收敛,我会强制使用另一个值 (1),并且我会为下一个图像情况打破循环。

import numpy 

res = zeros((len(range(0,5,1)),2)) #array of results

dX = 10. #my important value which allow stop loop for one "image"
n = 0 #number of iteration
itmax = 5. #my iteration max value 


#I have to achieve calculations on a great number of cases (image - and i want to store results of each case in "res array")

for image in range(0,5,1):

  a = randint(0,9) #for this example, i added a random value to treat the problem

  while abs(dX) > 5.: 

    dX = a - n

    if abs(dX) < 5.:
      res[image,0] = 100.
      res[image,1] = 100.

    elif n==itmax: 
      res[image,0] = 1.
      res[image,1] = 1.
      break

    n = n+1

res

但目前我总是得到零数组,因为它没有发生......

【问题讨论】:

    标签: python for-loop numpy while-loop break


    【解决方案1】:

    我仍然想知道您要做什么,但这段代码似乎已经更合理并且可以按照您的意愿工作:

    from __future__ import print_function
    
    import numpy as np
    import pylab
    
    nb_images = 5
    
    # array of results
    results = np.zeros([nb_images, 2])
    
    # my iteration max value
    itmax = 5.
    
    # I have to achieve calculations on a great number of cases (image -
    # and I want to store results of each case in "res array")
    for image in range(nb_images):
        # my important value which allow stop loop for one "image"
        dX = 10.
        # for this example, I added a random value to treat the problem
        a = pylab.randint(0, 9)
    
        print('dX:', dX, '(entering the while loop...)')
        n = 0
        while dX > 5:
            dX = a - n
            if dX < 5:
                results[image, :] = 100.
            elif n == itmax:
                results[image, :] = 1.
                break
            n += 1
            print('dX:', dX)
    
    print(results)
    

    除了修改以尊重pep 8(顺便说一句,您应该使用一个好的编辑器来帮助您指出简单的错误和样式问题。对于初学者来说一个好的编辑器是例如spyder),我将 dX = 10n = 0 移到 for 循环内,并删除 dX 条件中的 abs。我希望它能帮助你编写更好的 Python 代码。

    【讨论】:

    • 感谢您的帮助! ;) 但我问为什么我继续有一些值等于零......?对我来说,你只能有 1 或 100 作为值,这是我所期望的
    • 我想我必须指定
    猜你喜欢
    • 2013-04-11
    • 2016-01-11
    • 2018-03-02
    • 1970-01-01
    • 2016-02-13
    • 2021-05-19
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多