English 中文(简体)
Python州经过的辩词
原标题:Argument passing in Python
  • 时间:2012-05-23 01:22:24
  •  标签:
  • python

我不太明白变数当前_ label是怎么回事, 在我看来, 这似乎在随附的函数代码 ts_r 中被定义, 这将使它从 ts_r 内部可见? 但是当我运行下面的代码时, 它抱怨在指派前引用本地变数当前_ label... 注意它确实 不抱怨访问过或f, 如果我先用 [ lun(g)] 初始化当前_ 标签, 它不会抱怨 。

def topological_sort(g):

    visited = zeros((len(g)), dtype= int32 )
    f = zeros((len(g)), dtype= int32 )
    current_label = len(g) # [] so it is seen inside ts_r

    def ts_r(n):
        for nn in [v for v in g[n] if not visited[v]]:
            visited[nn] = 1
            ts_r(nn)
        f[n] = current_label
        current_label -= 1

    for i in range(len(g)):
        if not visited[i]: 
            ts_r(i)

    return f
最佳回答

visited f 的情况下,您可以改变变异变量 。在 current_ label 的情况下,您可以尝试将值重新分配给全球变量,而不声明它是全球性的 。

从外部范围变化的变数并不要求将其宣布为全球性的变数,但将值重新分配给一个全球性变数则要求将其宣布为全球性的变数 -- -- 否则,该变数被视为是局部性的(如果在分配前提供参考,则会发现此类差错)。

让我们看看代码:

1.    def ts_r(n):
2.        for nn in [v for v in g[n] if not visited[v]]:
3.            visited[nn] = 1
4.            ts_r(nn)
5.        f[n] = current_label
6.        current_label -= 1

5 的行中,您将全局变量值指定为 f[n] ,但后来在 6 的行中,您试图将这个全局变量指定为值。您没有告诉 Python 它是全球性的, 因此它假定它是本地的。 但如果是本地的, 您不能提前指定它 。

你有两个选择:

  1. 使用它作为本地:

    def ts_r(n):
        current_label = len(g)  # initialize local variable
        for nn in [v for v in g[n] if not visited[v]]:
            visited[nn] = 1
            ts_r(nn)
        f[n] = current_label
        current_label -= 1
    
  2. 告诉 Python 这是全局变量, 您想要更改全局变量 s 值 :

    def ts_r(n):
        global current_label  # current_label is now global
        for nn in [v for v in g[n] if not visited[v]]:
            visited[nn] = 1
            ts_r(nn)
        f[n] = current_label
        current_label -= 1
    

<强度 > EDIT :

您的问题更新后, 我看到嵌套函数, 而不是全球范围定义的函数。 因此, < code > global 的解决方案不会起作用 。

在 Python 3.x 中,您有 nonlocal 关键词,但您需要找到 Python 2.x 情况下的行走方式。 另外,您至少有两种可能性:

  1. 使用包含不可变的变量的可变变量,其中包含您想要更改的不可变变量(例如,列表中含有一个整数 ) 。 当您仅提及列表的第一个元素( 并更改) 时, 请尝试它 。

  2. 另一种解决办法是为包装功能添加属性( 函数也是可变的, 您可以更改它, 但您不会污染全球命名空间 ) 。 例如 : < a href=" http:// ideone.com/7jGvM" rel=“ nofollow” > http://ideone. com/7jGvM 。 您的情况可能是这样 :

    def topological_sort(g):
    
        visited = zeros((len(g)), dtype= int32 )
        f = zeros((len(g)), dtype= int32 )
        topological_sort.current_label = len(g) # [] so it is seen inside ts_r
    
        def ts_r(n):
            for nn in [v for v in g[n] if not visited[v]]:
                visited[nn] = 1
                ts_r(nn)
            f[n] = topological_sort.current_label
            topological_sort.current_label -= 1
    
        for i in range(len(g)):
            if not visited[i]: 
                ts_r(i)
    
        return f
    
问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...