嵌套for循环进行迭代

时间:2019-08-29 14:38:51

标签: python pandas numpy

matrix = np.zeros((106, 106))

for k in result:
    p = result[0]
    for j in result:
        q = result[1]
        matrix[result.index(k), result.index(j)] = frdist(p, q)
print(matrix)

我写了一些代码,现在我想迭代此代码,申请数据集。但是我得到了相同的结果。

为什么我得到相同的结果?

[[0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 ...
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]]

已更新:

RecursionError在此部分中发生。无法更改,因为它是algorithm的基本组成部分。有什么想法吗?

__all__ = ['frdist']


def _c(ca, i, j, p, q):

    if ca[i, j] > -1:
        return ca[i, j]
    elif i == 0 and j == 0:
        ca[i, j] = np.linalg.norm(p[i]-q[j])
    elif i > 0 and j == 0:
        ca[i, j] = max(_c(ca, i-1, 0, p, q), np.linalg.norm(p[i]-q[j]))
    elif i == 0 and j > 0:
        ca[i, j] = max(_c(ca, 0, j-1, p, q), np.linalg.norm(p[i]-q[j]))
    elif i > 0 and j > 0:
        ca[i, j] = max(
            min(
                _c(ca, i-1, j, p, q),
                _c(ca, i-1, j-1, p, q),
                _c(ca, i, j-1, p, q)
            ),
            np.linalg.norm(p[i]-q[j])
            )
    else:
        ca[i, j] = float('inf')

    return ca[i, j]

1 个答案:

答案 0 :(得分:1)

您要enumerate

for k, p in enumerate(result):
    for j, q in enumerate(result):
        matrix[k, j] = frdist(p, q)