我目前正在嘗試為 Random Walks 迭代陣列,并且當陣列的每個元素有多個數字時,我可以使用 for 回圈。我似乎無法將 math.dist 函式應用于每個元素一個數字的一??維陣列。
這是有問題的代碼:
origin = 0
all_walks1 = []
W = 100
N = 10
list_points = []
for i in range(W):
x = 2*np.random.randint(0,2,size=N)-1
xs = cumsum(x)
all_walks1.append(xs)
list_points.append(xs[-1])
list_dist = []
for i in list_points:
d = math.dist(origin, i)
list_dist.append(d)
如果我嘗試將距離附加到新陣列,則會收到TypeError: 'int' object is not iterable錯誤。
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1808/1512057642.py in <module>
16
17 for i in list_points:
---> 18 d = math.dist(origin, i)
19 list_dist.append(d)
20
TypeError: 'int' object is not iterable
但是,如果我在 for 回圈中決議的陣列每個元素有多個數字,就像在下面的代碼中一樣,那么一切正常:
origin = (0, 0, 0)
all_walks_x = []
all_walks_y = []
all_walks_z = []
W = 100
N = 10
list_points = []
for i in range(W):
x = 2*np.random.randint(0,2,size=N)-1
y = 2*np.random.randint(0,2,size=N)-1
z = 2*np.random.randint(0,2,size=N)-1
xs = cumsum(x)
ys = cumsum(y)
zs = cumsum(z)
all_walks_x.append(xs)
all_walks_y.append(ys)
all_walks_z.append(zs)
list_points.append((xs[-1], ys[-1], zs[-1]))
list_dist = []
for i in list_points:
d = math.dist(origin, i)
list_dist.append(d)
I have tried using for i in range(len(list_points): and for key, value in enumerate(list_points): to no success. The only difference between the first and and the second list_points arrays would appear to be the elements enclosed in parentheses when there are multiple numbers per element. It would seem to be a simple solution that in whatever way is eluding me. Thanks for reading, and any help would be appreciated.
EDIT: I may be using the terms 1D and 3D arrays incorrectly, The first array is a list of numbers such as [6, 4, -1, 5 ... ] and the second array is a list of multiple numbers per element such as [(-10, -2, 14), (12, 2, 8), (-4, 8, 24), (10, 10, 0), (2, 8, 10) ... ]
uj5u.com熱心網友回復:
看來您正在將整數傳遞給 math.dist。math.dist 找到一維點和二維點之間的歐幾里得距離。因此,您必須提供一個串列,即使它只是一個整數。
例子:
# not valid
math.dist(1, 2)
# valid
math.dist([1], [2])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424164.html
標籤:python arrays numpy iteration typeerror
下一篇:更新numpy陣列的值
