试图在python3中使用全局字典

时间:2015-01-22 20:02:58

标签: python dictionary global-variables primes

我正在尝试在python3中创建一个全局字典来存储一组正在进行的键值对。出于某种原因,我说:

1 10
[1, 10]
1 10
Traceback (most recent call last):
  File "prime1.py", line 51, in <module>
    m = [dict_check(i) for i in inPut]
  File "prime1.py", line 51, in <listcomp>
    m = [dict_check(i) for i in inPut]
  File "prime1.py", line 17, in dict_check
    if not num2 in d:
UnboundLocalError: local variable 'd' referenced before assignment

这是我的代码:

#!/usr/bin/env python3

from sys        import stdin
from math       import sqrt

d = {}
def dict_check(num) :
    print (num)
    if len(num) != 2:
        num1 = num2 = num[0]
    else :
        num1,num2 = num 
        print(num1,num2)
    primes = []
    if num1 > num2 :
        num1, num2 = num2, num1 
    if not num2 in d:
        while num2 >= 1 :
            if num2 in d:
                primes += d[num2]
                break       
            else :
                if is_prime(num2) :
                    primes += [num2]
                num2 -= 1
        d += {num2:primes}  
    newList = []
    print(d)
    for l in d[num2] :
        if l < num1 :
            break
        newList += [l]  
    return sorted(newList)     



def is_prime (n) :
    assert n > 0
    if n == 1 :
        return False
    if n == 2 :
        return True
    if (n % 2) == 0 :
        return False
    for i in range(3, int(sqrt(n)) + 1, 2) :
        if (n % i) == 0 :
            return False
    return True 

if __name__ == "__main__" :

    inPut = ([int(v) for v in s.split()] for s in stdin)
    m = [dict_check(i) for i in inPut]
    for v in zip(*m) :
        v = v
        print(v[0])

我不明白为什么这会给我错误。我已经在def之外宣布它,所以它应该是全局的。我以前做过这件事,似乎没有用。

2 个答案:

答案 0 :(得分:0)

d += {num2:primes}对python不明确。 d是左侧的本地区域和右侧的全局区域。您可以通过将global d放在函数顶部来解决问题。

def dict_check(num) :
    global d
    ...

答案 1 :(得分:0)

全局变量在更改其值时必须使用“global”关键字。

YourDict = {"Key1", "Value1"}

def Change():
    global YourDict
    YourDict.keys["Key1"] = "Value2"