【问题标题】:Error message: 'list' object is not callable in python3错误消息:'list' 对象在 python3 中不可调用
【发布时间】:2018-10-21 23:22:54
【问题描述】:

我正在研究遗传算法中的循环交叉。这个想法是针对给定的父 [4,1,6,2,3,5,8,9,7,10], [1,2,3,4,5,6,7,8,9,10] ,我必须从中获得一个孩子。谁能告诉我为什么它说,“TypeError: 'list' object is not callable " 在下面的代码中。

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]]

【问题讨论】:

  • 消息所指代码的哪一部分?
  • 当我取消注释第一个返回并评论第二个返回时,它运行良好。但显然它只提供循环。但是我需要孩子!
  • cycle = []from itertools import cycle。您对两个对象使用相同的名称。
  • 通常情况下,这是完全错误的,但请注意cycle = [] 在 while 循环内部,而他试图从外部调用函数?如果您来自其他语言,您希望它仍然可以工作,因为块范围是一回事。可悲的是,Python 没有 有这样的东西。处理它并正确命名您的变量,循环和循环不是正确的变量名称。

标签: arrays python-3.x numpy permutation


【解决方案1】:

调试 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

我们希望看到回溯,而不仅仅是错误消息。我们需要知道错误发生的WHERE,而不仅仅是它所说的。

该错误意味着某个具有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 列表的工作,然后从不使用它?

你是不是只是从某个地方复制了函数,但没有调试它?

【讨论】:

    猜你喜欢
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 2014-06-13
    • 2022-11-01
    • 1970-01-01
    • 2015-11-11
    • 2022-12-14
    相关资源
    最近更新 更多