我無法使用 Python 中的函式將字串拆分為串列。但是,當我在沒有函式的情況下執行此操作時,它可以作業。這是我的代碼:
def listAdder(list1):
""" Function to split a string into a list. """
text_line = "This is a string"
list1 = text_line.split(' ')
print(list1) # printing the list to verify its status within the function.
list1 = []
listAdder(list1)
print(len(list1)) # printing the length of the list to verify its status outside the
# function
輸出:
['This', 'is', 'a', 'string']
0
從輸出中可以明顯看出,串列已成功創建,其中字串元素在函式內拆分。但是,當我嘗試從函式中驗證其狀態時,該串列仍為空。
我需要做什么才能使串列在函式之外保留其值?
編輯:得到解決方案:
def listAdder(list1=[]):
text_line = "This is a string"
list1 = text_line.split(' ')
print(list1)
return list1
list1 = listAdder()
print(len(list1))
這按預期作業!謝謝
uj5u.com熱心網友回復:
您必須將更新的串列(通過您的函式)分配給主程式中的變數,如下所示。在 listAdder 函式內部,當您分配 split 函式的結果時,初始串列參考丟失,因此對您的程式主體不可見。
def listAdder(list1):
text_line = "This is a string"
list1 = text_line.split(' ')
print(list1) # printing the list to verify its status within the function.
return list1
list1 = listAdder(list1)
print(len(list1))
uj5u.com熱心網友回復:
這是因為變數的范圍。更新list1在功能不更新函式的范圍之外的物件。
您可以使用不帶引數的函式并用 標記它global list1,這允許它更改list1您在全域范圍內宣告的內容。
def listAdder():
global list1 # This allows it to modify the variable
""" Function to split a string into a list. """
text_line = "This is a string"
list1 = text_line.split(' ')
list1 = []
listAdder() # No parameter
print(len(list1)) # Prints 4
然而,這被認為是糟糕的做法,因為它可能更難推理我們的代碼。
最好使用函式回傳值。
def listAdder():
text_line = "This is a string"
return text_line.split(' ')
list1 = []
list1 = listAdder()
uj5u.com熱心網友回復:
list1insidelistAdder是區域變數,與list1您在外部創建的內容無關listAdder
要使用您應該使用的相同變數global,然后您不需要定義引數
def listAdder():
global list1 # inform function to use global variable when you use `=`
text_line = "This is a string"
list1 = text_line.split(' ')
print(list1)
list1 = [] # it is global variable
listAdder()
print(len(list1))
但更好的是使用return將結果發送回主代碼。它也不需要list1作為引數。在函式內部,我使用不同的名稱來表明它是不同的變數
def listAdder():
text_line = "This is a string"
text_list = text_line.split(' ')
print(text_list)
return text_list
list1 = listAdder()
print(len(list1))
如果你想發送一些串列來運行并在這個串列中得到結果,那么你應該使用append()or extend()(or =) 而不是=
def listAdder(text_list):
text_line = "This is a string"
#text_list.extend( text_line.split(' ') )
text_list = text_line.split(' ')
print(text_list)
list1 = []
listAdder(list1)
print(len(list1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/344636.html
