Skip to main content
 首页 » 编程设计

python之Itertools 不可调用

2024年11月01日9linjiqin

今天我在执行 How to get all possible combinations of a list’s elements? 时遇到了一个奇怪的错误Dan H. 的解决方案。 我不断收到此错误:

TypeError: 'itertools.combinations' object is not callable

有谁知道这是为什么以及如何解决?我使用以下代码:

def all_subsets(ss): 
           return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1))) 
 
for subset in all_subsets([1,2,3,4]): 

在此之后我得到一个错误。谁能帮帮我?

编辑1:

人们要求完整的代码,所以这里是代码错误的一些相关部分:

from scapy.all import * 
import itertools 
from itertools import * 
 
def all_combinations(input): 
  return chain(*map(lambda y: combinations(input, y), range(0, len(input)+1))) 
 
extensionHeader=["IPv6ExtHdrHopByHop","IPv6ExtHdrRouting","IPv6ExtHdrDestOpt","IPv6ExtHdrFragment"] 
ip=IPv6(src="2a00:1450:4009:807::1002", dst="2a00:1450:4009:807::1002") 
combinations = itertools.combinations(extensionHeader, 1) 
 
 
for subset in all_combinations(extensionHeader): 
    index=0 
    finalForm="" 
    while index<len(subset): 
        substring=subset[index:index+17] 
        if substring is "IPv6ExtHdrRouting": 
            if index==0: 
                ip.nh=43 

这里还有完整的错误:

WARNING: No route found for IPv6 destination :: (no default route?) 
Traceback (most recent call last): 
  File "C:\Users\Martinooos\workspace\testing\scapyTest.py", line 18, in <module 
> 
    for subset in all_combinations(extensionHeader): 
  File "C:\Users\Martinooos\workspace\testing\scapyTest.py", line 11, in all_com 
binations 
    return chain(*map(lambda y: combinations(input, y), range(0, len(input)+1))) 
  File "C:\Users\Martinooos\workspace\testing\scapyTest.py", line 11, in <lambda 
> 
    return chain(*map(lambda y: combinations(input, y), range(0, len(input)+1))) 
TypeError: 'itertools.combinations' object is not callable 

请您参考如下方法:

编辑:

这是你的问题:

combinations = itertools.combinations(extensionHeader, 1) 

您不想将结果保存到组合中,因为这样当您尝试在 all_combinations() 中使用 combinations() 函数时,Python 将尝试将您的组合变量用作函数,因此您会收到错误消息:

'itertools.combinations' object is not callable

要修复,只需将您的变量重命名为其他名称,例如:

combs = itertools.combinations(extensionHeader, 1) 

或修改您的 all_combinations() 以使用 itertools.combinations 而不仅仅是 combinations:

def all_combinations(input): 
  return itertools.chain(*map(lambda y: itertools.combinations(input, y), range(0, len(input)+1)))