我试图使用lattice函数随机遍历一个名为randrange的矩阵。我的矩阵是8x8,打印得很好。然而,当我试图随机循环这个矩阵的每一个元素时,我就得到了错误。
'TypeError:'int‘对象不可迭代’
由于范围的上限,len(mymatrix)。我不知道这是为什么。
for R1 in randrange(0, (len(lattice)):
for R2 in randrange(0, len(lattice)):
H = -j*lattice[R1,R2]*(lattice[R1+1,R2],lattice[R1-1,R2], lattice[R1,R2+1],lattice[R1,R2-1]) +h*lattice[R1,R2]
H_flip = -j*-1*mymatrix[R1,R2]*(lattice[R1+1,R2],lattice[R1-1,R2], lattice[R1,R2+1],lattice[R1,R2-1]) +h*lattice[R1,R2]
print lattice[R1,R2]我以前没有在循环中使用过randrange,难道它不能像使用范围那样使用吗?我还试图将范围设置为:
for R1 in randrange(0, len(lattice)-1)我想也许这个长度太长了,但没有用。
发布于 2018-01-05 14:21:48
方法randrange不返回一个范围,而是一个随机选择的元素,它可以在文档中读取。
random.randrange(start, stop[, step])从range(start, stop, step)中返回随机选择的元素。这相当于choice(range(start, stop, step)),但实际上并不构建range对象。
这就是为什么您得到了一个TypeError,您确实试图在一个int上循环。
我不建议在列表上按随机顺序循环,但是如果有必要的话,我会使用shuffle。
from random import shuffle
# shuffle mutates your list so we need to do the following
rows, cols = range(len(lattice)), range(len(lattice))
shuffle(rows)
shuffle(cols)
for R1 in rows:
for R2 in cols:
# ...注意,在Python3中,首先需要将range转换为list。
发布于 2018-01-05 14:31:45
你是对的。randrange()从给定范围内返回单个元素。另一方面,range()返回元素列表,因此是可迭代的。
你可以试试这样的方法:
stop = randrange(0, len(lattice)-1)
start = randrange(0, stop)
for R1 in randrange(start, stop):
for...https://stackoverflow.com/questions/48115384
复制相似问题