擅长:python、mysql、java
<p><strong>检查第一个示例。</strong></p>
<pre><code>global lst
lst=[]
def function1():
lst.append(6)
print(lst)
def function2():
lst.append(7)
print(lst)
function1()
function2()
</code></pre>
<p><strong>输出:-</strong></p>
<pre><code>C:\Python34\python.exe "C:/Users/akthakur/PycharmProjects/Learning python/testing.py"
[6]
[6, 7]
</code></pre>
<p>在这里,lst被声明为global,并在函数1中使用,在函数2中使用时,使用相同的lst,因此输出。你知道吗</p>
<p><strong>第二个示例</p>
<pre><code>global lst
lst=[]
def function1():
lst=[7,8]
lst.append(6)
print(lst)
def function2():
lst.append(7)
print(lst)
function1()
function2()
</code></pre>
<p><strong>输出</strong></p>
<pre><code>C:\Python34\python.exe "C:/Users/akthakur/PycharmProjects/Learning python/testing.py"
[7, 8, 6]
[7]
</code></pre>
<p>现在,正如您在function1<strong>lst=[7,8]</strong>中定义的那样,这将创建一个新的本地列表lst,在function1中使用了相同的列表(本地版本),在function2中,当您再次调用lst时,将调用其全局版本。[这就是您要做的。]</p>
<p>因此,与其将新的本地列表声明为<strong>lst=['12','10']</strong>,不如将值附加到函数外部定义的现有列表中,并将其声明为global。你知道吗</p>