所以有一天我因为拼写错误而陷入困境。而不是迭代我的嵌套循环与i + = 1我使用i = + 1。在我开始打印步骤数量并看到它连续打印步骤1之前,我没有注意到这一点。因此我得到的情节没有任何意义。
然而,我不明白为什么我会得到任何情节,并且代码没有陷入无限循环?此外,我应该只是在步骤数量的中途计算数据,所以我根本不了解我的数据。或者我= + 1意味着别的什么?我似乎无法在网上找到关于i = + 1的更多信息
这是原始代码的精简版本:
for temp in np.linspace(1.0,4.0,num=100):
energyarray = []
for step in np.arange(0, sw*2):
for i in range(n-1):
for j in range(n-1):
H_old = -J*matrix[i,j]*(matrix[i,j-1] + matrix[i,j+1] + matrix[i-1,j] + matrix[i+1,j])
H_new = J*matrix[i,j]*(matrix[i,j-1] + matrix[i,j+1] + matrix[i-1,j] + matrix[i+1,j])
del_H = H_old-H_new
if del_H >= 0:
matrix[i,j] = -matrix[i,j]
elif del_H < 0:
prob = np.exp((del_H)/(temp))
rand = random.random()
if rand < prob:
matrix[i,j] = -matrix[i,j]
else:
matrix[i,j] = matrix[i,j]
if step >= (sw):
Ene = EnergyCal(matrix)
energyarray.append(Ene)
step =+ 1
energy_sum = []
energy_sum = sum(energyarray)
plt.figure(10)
plt.plot(temp, energy_sum, 'ro')
plt.show()
答案 0 :(得分:3)
Python for循环是基于迭代器的“for-each”循环。迭代变量在每次迭代开始时重新分配。换句话说,以下循环:
In [15]: nums = 1,2,5,8
In [16]: for num in nums:
...: print(num)
...:
1
2
5
8
相当于:
In [17]: it = iter(nums)
...: while True:
...: try:
...: num = next(it)
...: except StopIteration:
...: break
...: print(num)
...:
1
2
5
8
同样,以下循环是等效的:
In [19]: for num in nums:
...: print("num:", num)
...: num += 1
...: print("num + 1:", num)
...:
...:
num: 1
num + 1: 2
num: 2
num + 1: 3
num: 5
num + 1: 6
num: 8
num + 1: 9
In [20]: it = iter(nums)
...: while True:
...: try:
...: num = next(it)
...: except StopIteration:
...: break
...: print("num:", num)
...: num += 1
...: print("num + 1:", num)
...:
num: 1
num + 1: 2
num: 2
num + 1: 3
num: 5
num + 1: 6
num: 8
num + 1: 9
注意,Python中不存在C风格的for循环,但是你总是可以编写一个while循环(循环的c风格基本上是while循环的语法糖):
for(int i = 0; i < n; i++){
// do stuff
}
相当于:
i = 0
while i < n:
# do stuff
i += 1
注意,不同之处在于,在这种情况下,迭代取决于i
,# do stuff
中修改i
的任何内容都会影响迭代,而在前一种情况,迭代取决于迭代器。注意,如果我们修改迭代器,那么迭代会受到影响:
In [25]: it = iter(nums) # give us an iterator
...: for num in it:
...: print(num)
...: junk = next(it) # modifying the iterator by taking next value
...:
...:
1
5
答案 1 :(得分:2)
step
覆盖 for
for step in np.arange(0, sw*2):
step = 1 # doesn't matter, it'll get reset on next iteration