【发布时间】:2021-10-30 08:33:05
【问题描述】:
我无法使用 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))
这按预期工作!谢谢
【问题讨论】:
-
您是否尝试将
return list1添加到您的函数并使用list1 = listAdder(list1)检索返回的列表或将global list1添加到您的函数? -
在函数开头添加
global text_line。 -
尝试添加一个 return 语句
return list1并在调用函数时将函数的返回值存储在一个新列表中。它有效! -
@marcelh 这行得通:
def listAdder(list1=[]): text_line = "This is a string" list1 = text_line.split(' ') print(list1) return list1 list1 = listAdder() print(len(list1)) -
您使用可变默认参数的“解决方案”是一个新的、不同的错误等待咬您,而不是解决您的问题。追加到您的列表或返回您创建的新本地列表。