Python - 带有嵌套循环的属性特定值

Python - attribute specific values with imbricated loops

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

对于每个 "image",我必须计算 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

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

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

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 (And by the way, you should use a good editor that helps you by pointing out simple errors and style problems. A good editor for beginners is for example spyder) 而进行的修改外,我在 for 循环中移动了 dX = 10n = 0,并删除了 [=14] 条件中的 abs =].我希望它能帮助您编写更好的 Python 代码。