itertools

时间:2016-05-19 14:53:13

标签: python list itertools

import itertools

#p = input()

def fac(n):
    factorlist = []
    k = 1
    while k < n+1:
        if n % k == 0:
            factorlist.append(k)
            k+=1
            continue
        else:
            k+=1
            continue
    print factorlist
    return factorlist

for a, b in itertools.combinations(factorlist,2):
    if gcd(a,b) == 1:
        print a,b
        continue
    else:
        continue

n=0
while n<=100:
fac(n)
n+=1

在上面的代码中,当我尝试运行itertools.combination时,错误告诉我factorlist没有定义,即使我在函数定义中返回它并且我能够打印它。

1 个答案:

答案 0 :(得分:0)

首先需要调用该函数并将值输入factorlist变量。它存在于函数fac的本地范围内,但不是全局存在的。要修复它,首先运行fac并将返回值分配给主范围的变量factorlist。然后,您将能够无错误地运行for循环:

factorlist = fac(some_value)
for a, b in itertools.combinations(factorlist,2):
    do_things