【问题标题】:Why can't I use the split() method in Python to split a string into a list from within a function?为什么我不能在 Python 中使用 split() 方法将字符串从函数中拆分为列表?
【发布时间】: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))
  • 您使用可变默认参数的“解决方案”是一个新的、不同的错误等待咬您,而不是解决您的问题。追加到您的列表或返回您创建的新本地列表。

标签: python list function


【解决方案1】:

您必须将更新后的列表(通过您的函数)分配给主程序中的变量,如下所示。在 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))

【讨论】:

    【解决方案2】:

    这是因为变量的作用域。在函数中更新 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()
    

    【讨论】:

    • 谢谢。这是一个恰当的解释。
    【解决方案3】:

    list1 inside listAdder 是局部变量,它与您在listAdder 之外创建的list1 无关

    要使用相同的变量,您应该使用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()extend()(或+=)而不是=

    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))
    

    【讨论】:

      猜你喜欢
      • 2011-12-29
      • 2013-05-14
      • 1970-01-01
      • 2013-09-10
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多