[英]Pass a List into Python Function
作為一名新的 Python 程序員,我有兩個關於 list 的問題,非常感謝您的建議:
問題 1:
對於以下代碼:
nums1 = [1,2,3,8,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
def merge(nums1, m, nums2, n):
nums1[:] = sorted(nums1[:m]+nums2)
merge(nums1, m, nums2, n)
nums1
它的作用是:將列表 nums1 和列表 nums2 傳遞到合並函數中,並將它們與列表 nums1 合並到列表 nums1 中,其中 nums1 中的前 m 項和 nums2 中的 n 項,並對列表 nums1 進行排序。 所以結果是: [1, 2, 2, 3, 5, 6] 所以我的問題是:既然列表 nums1 是在函數合並的范圍之外定義的,它為什么有更新 nums1 的能力? 在以下示例中:
x = 10
def reassign(x):
x = 2
reassign(x)
x
變量 x 是在函數 reassign 之外定義的,而 reassign 函數無法更新在 reassign 之外定義的 x,這就是 x 返回 10 的原因。
問題2:
在我提供的上面的代碼中,如果我像下面這樣寫:
注意:我只是在分配 sorted(nums1[:m]+nums2) 時將 nums1[:] 修改為 nums1
nums1 = [1,2,3,8,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
def merge(nums1, m, nums2, n):
nums1 = sorted(nums1[:m]+nums2)
merge(nums1, m, nums2, n)
nums1
nums1 返回 [1,2,3,8,0,0,0],所以我的問題是:在 nums1 后添加 [:] 后,為什么函數有 nums1 的能力? 在那個例子中 [:] 是什么?
要復制您所說的內容,請執行以下操作:
var = 10
lst = [1, 2, 3]
def func():
var = 11
lst[:] = [1, 2, 3, 4]
func()
print(var, lst)
以上將輸出10 [1, 2, 3, 4]
。 現在注意以下幾點:
var = 10
lst = [1, 2, 3]
def func():
print(var)
print(lst)
func()
輸出10 [1, 2, 3]
-- 所以我們知道函數可以訪問全局變量,但在大多數情況下不能修改它們。 現在讓我們看看這兩種情況( int
和list
): 兩種情況如下:
var
變量沒有被修改(雖然我們可以訪問全局作用域,但我們不能修改它)。 我建議使用打印globals()
和locals()
來獲得樂趣。 如果我們這樣做,則可以修復這種情況:def func():
global var
var = 11
[:]
表示法修改lst
變量,因為正如此處所引用的,切片賦值[:]
使用operator
函數setitem()
。 因此,從技術上講, lst[:] =
相當於:from operator import setitem
lst = [1, 2, 3]
# Both of these are equivalent.
lst[:] = [1, 2, 3, 4]
setitem(a, slice(0, len(a)), [1, 2, 3, 4])
setitem
不區分本地或全局范圍。
(不要使用[:]
東西。這太可怕了。)
當您說nums1[:]
Python 正在查找名為nums1
的 GLOBAL 列表。 然而,在函數內部,Python 首先關注新變量。 為什么?
- 如果您在函數之外的任何變量名稱現在被限制用作函數內部的 DIFFERENT 變量,那將會很糟糕
H = True # some variable.pretend it means "High"
def euro_height(inches):
H = inches # since H is a nice abbrev for height in inches
return H*2.54 # Centimeters
我不希望函數中的H
覆蓋我已經存儲的內容。 因此,在euro_height
, H
被視為不同的局部變量,只有該函數才能看到和使用。 如果我想從函數外部使用H
,我必須首先告訴 Python 訪問它。 那我就可以用了。
H = True # some variable.pretend it means "High"
def euro_height(inches):
global H
print(H) # will say true
renamed_var = inches # since H is a nice abbrev for height in inches
return renamed_var*2.54 # Centimeters
如果我現在在函數內部分配H = inches
,它將覆蓋全局H
的True
值。 因此,我將其重命名,因為已經有一個H
我想使用。
所有這些的名稱稱為namespaces 。 希望你正在做一個 Python 教程。 當他們教授函數時,你會明白這一點。 如果你不是,我建議你做一個教程。
有關與您發生的事情相關的此答案的更多信息,請查看此處的交互式示例https://www.programiz.com/python-programming/global-local-nonlocal-variables
另外,永遠不要再次使用mylist[:]
。 =) 這是糟糕的語法。 它只返回整個列表。 所以只需使用列表mylist
的名稱。 通過添加括號,您強制查找全局變量,並創建了您的問題
如果您感到困惑,請執行以下操作。
首先安置和改變不是一回事
nums1 = [1,2,3,8,0,0,0]
lst = None
m = 3
nums2 = [2,5,6]
n = 3
def merge(nums1, m, nums2, n):
global lst
lst = sorted(nums1[:m]+nums2)
merge(nums1, m, nums2, n)
print(lst)
nums1[:]
表示您的整個列表。 如果您使用nums1[:]
而不是nums1
您可以使用sorted(nums1[:m]+nums2)
更改以前的nums1[:]
列表。 當你這樣做時,你的前一個和最新的列表nums1
改變,所以你在nums1
數組列表中用新的附加變量更改 new 。 但是如果你只使用nums1
而不是nums1[:]
最新的nums1
現在指的是一個與前者不同的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.