【问题标题】:How do I update a variable (which is a list) with an updated list after using a function to alter it? [duplicate]在使用函数更改变量后,如何使用更新的列表更新变量(这是一个列表)? [复制]
【发布时间】:2017-03-28 21:24:01
【问题描述】:

我需要一些帮助,我已经编写了一些代码,应该使用函数来操作列表。我遇到的问题是保留这个被操纵的列表以在主要编码中使用。例如,我创建了一个列表,其中包含 4 个排队购票的人的姓名,然后我将此列表输入到函数中以删除第 3 个排队的人。这将创建一个新列表,我希望能够在函数之外对其进行操作。到目前为止,这是我的代码

def aLeave(aList,usrstr):

    tempq = []
    idx = 0
    found = False
    while idx < len(aList) and not found: #This section works out the index
        if aList[idx] == usrstr:          # of the user string that needs removed
            found = True                  # from the queue list.
        else:
            idx = idx + 1

    if found:        
        for i in range(len(aList)):           #This sections takes the index previously 
            if i == idx:                      #found and uses it to create a new list
                continue                      #without the element the user has requested to be removed
            tempq.append(aList[i])

    aList = tempq
    print(aList)
    return aList

aList = ["john","mark","pete","dave"]

aLeave(aList,input("what do you want to remove"))

print (aList)

任何帮助将不胜感激!

谢谢(这个函数叫做'aLeave')

【问题讨论】:

  • aList 是您函数内部的一个局部变量。分配给它不会修改全局aList。您可以在函数顶部使用global aList,但这是糟糕的设计。相反,您应该只是return 列表,就像您一样。但是,您必须执行类似aList = aLeave(aList, input('...')) 的操作,否则返回值不会分配给任何东西,不再被引用,并且会被垃圾收集。您也可以只使用 return tempq 并在函数中省略 aList = tempq
  • 另外,你真的不需要使用两个循环来完成你正在做的事情。只需for x in aList: if x != usrstr: tempq.append(x)
  • 感谢@juanpa.arrivillaga 我意识到在我编写代码之后可以更简单地完成它。我会尝试你的建议。

标签: python list python-3.x


【解决方案1】:

您只需将函数的返回值分配给一个变量,并且由于您想更新同一个列表,您可以在调用函数时执行类似的操作。

aList = aLeave(aList, input("Stuff"))

此外,在函数内部,aList = tempq 不是必需的,因为它所做的只是更新局部变量 aList。要在全局范围内更新aList,可以在函数顶部写global aList,但这不是好的设计实践,应尽量避免。

【讨论】:

  • 谢谢@Shubham Jindal。我有额外的代码行来尝试让它工作。已经对其进行了精简并设法返回了新列表。 :)
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
相关资源
最近更新 更多