【发布时间】: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