错误消息:“列表”对象在python3中不可调用

时间:2018-10-21 23:22:55

标签: arrays python-3.x numpy permutation

我正在研究遗传算法中的循环交叉。这个想法是针对给定的父项[4,1,6,2,3,5,8,9,7,10][1,2,3,4,5,6,7,8,9,10],我必须从中获取一个孩子。谁能告诉我为什么它说“ TypeError:'list'对象不可调用” 在以下代码中。

import numpy as np
import random
from itertools import cycle, permutations


def cx(individual):
    c = {i+1: individual[i] for i in range(len(individual))}
    cycles = []
    xx = sorted(individual)
    newArray = np.array([xx,individual])

    while c:
        elem0 = next(iter(c)) # arbitrary starting element
        this_elem = c[elem0]
        next_item = c[this_elem]

        cycle = []
        while True:
            cycle.append(this_elem)
            del c[this_elem]
            this_elem = next_item
            if next_item in c:
                next_item = c[next_item]
            else:
                break

        cycles.append(cycle)

    #return cycles
    return [[d[i] for i in range(len(d))] for l in permutations(newArray) for d in ({p[n]: n for s, p in zip(c, cycle({n: i for i, n in enumerate(s)} for s in l)) for n in s},)]

print (cx([4,1,6,2,3,5,8,9,7,10]))

我希望它返回[[1, 2, 6, 4, 3, 5, 7, 8, 9, 10], [4, 1, 3, 2, 5, 6, 8, 9, 7, 10]]

1 个答案:

答案 0 :(得分:0)

调试101:

1822:~/mypy$ python3 stack52920742.py 
Traceback (most recent call last):
  File "stack52920742.py", line 32, in <module>
    print (cx([4,1,6,2,3,5,8,9,7,10]))
  File "stack52920742.py", line 30, in cx
    return [[d[i] for i in range(len(d))] for l in permutations(newArray) for d in ({p[n]: n for s, p in zip(c, cycle({n: i for i, n in enumerate(s)} for s in l)) for n in s},)]
  File "stack52920742.py", line 30, in <listcomp>
    return [[d[i] for i in range(len(d))] for l in permutations(newArray) for d in ({p[n]: n for s, p in zip(c, cycle({n: i for i, n in enumerate(s)} for s in l)) for n in s},)]
TypeError: 'list' object is not callable

我们要查看回溯,而不仅仅是错误消息。我们需要知道错误发生的位置,而不仅仅是说错了。

该错误表示某些具有list值的变量被视为函数。也就是说,列表后跟(...)。列表不是函数,不是callable。它们只能被索引,在Python中使用[]语法。

可能的候选人是

cycle({n: i for i, n in enumerate(s)} for s in l)

它看起来像是在调用cycle函数,带有一个元组的字典。但是如果cycle是一个列表,则会产生此错误。

cycle是什么?

from itertools import cycle

而且

cycle = []

很明显,第二个任务正在覆盖第一个任务。

如果我将内部cycle重命名为alist之类的东西,尽管打印是正确的,它仍会运行

[[], []]

cycles在长return之前是

[[4, 2, 1], [6, 5, 3], [8, 9, 7], [10]]

为什么cx会去完成创建此cycles列表的所有工作,然后再不使用它呢?

您只是从某个地方复制了功能,但没有调试它吗?