Simple 1D Array Iteration Error (TypeError: 'int' object is not iterable)

Simple 1D Array Iteration Error (TypeError: 'int' object is not iterable)

我目前正在尝试为随机游走迭代数组,当数组的每个元素有多个数字时,我可以使用 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)

我尝试使用 for i in range(len(list_points):for key, value in enumerate(list_points): 没有成功。第一个和第二个 list_points 数组之间的唯一区别似乎是当每个元素有多个数字时括在括号中的元素。它似乎是一个简单的解决方案,无论如何都在躲避我。感谢阅读,我们将不胜感激。

编辑:我可能错误地使用了术语 1D 和 3D 数组,第一个数组是数字列表,例如 [6, 4, -1, 5 ... ],第二个array 是每个元素的多个数字的列表,例如 [(-10, -2, 14), (12, 2, 8), (-4, 8, 24), (10, 10, 0), (2, 8, 10) ... ]

您似乎将整数传递给 math.dist。 math.dist 求一维点和二维点之间的欧氏距离。因此,您必须提供一个列表,即使它只是一个整数。

示例:

# not valid
math.dist(1, 2)

# valid
math.dist([1], [2])