关于Python函数和列表的混淆

时间:2016-09-26 19:15:32

标签: python

我正在尝试创建一个函数,用于通过指定的索引或传递的项目从传递的列表中删除项目。

如果用户希望使用索引从列表中删除项目,则传递的第三个参数将为“index”,如果用户希望使用传递的项目删除列表中找到的第一个项目,则第二个参数参数将是“{item}”

例如,要从列表中删除索引3处的项目,这将是命令myFunction(myList,3,”index”)

我对这个功能部分感到很困惑。我编写的代码完全可以解决问题,但它不使用函数。我的代码如下:

mylist = ["one" , "two" ,"three" , "four" , "five"]
print "list is composed of: "+ str(mylist)
name = raw_input("Index of item to be removed. ex.  1")
name2 = raw_input('"item to be removed. ex. four')
name3 = int(name)
del mylist[name3]
mylist.remove(name2)
print mylist

看来我需要创建一个函数来执行此操作,然后传入我的列表,索引/项目等)但我在此部分非常迷失。

3 个答案:

答案 0 :(得分:1)

你真的需要处理你的问题解决技巧。很难理解你想要完成的事情。在做了大约六个假设之后,我认为这就是你要做的事情:

def listRemover(mylist,index_or_name,mytype):
    if mytype == "index":
        del mylist[index_or_name]

    if mytype == "name":
        mylist.remove(index_or_name)

很明显,你对python的基本知识存在一些漏洞。您需要研究函数是什么,它们有用的原因以及如何使用它们。

答案 1 :(得分:1)

  

看来我需要创建一个函数来执行此操作,然后传入我的列表,索引/项目等)但我在此部分时非常迷失。

Google it!(query =“define function python”)

展示您的研究。函数的基本形式是:

def funcname(arg1, arg2, arg3):
   # now you can use the vars arg1, arg2, and arg3.
   # rename them to whatever you want.
   arg1[0] = "bannanas"

所以,

array = ['mango', 'apple']
funcname(array)
print(array) # -> ['bannanas', 'apple']

答案 2 :(得分:1)

问题(我认为)是:" 如果用户希望使用索引从列表中删除项目,则传递的第三个参数将是“index”,如果用户希望删除使用传递的项目在列表中找到的第一个项目,第二个参数将是“{item}”"

本练习的目的(大概)是练习编写一个函数。是的,你可以在没有功能的情况下完成它,但现在你需要编写一个函数和传递参数的做法。函数是编程中非常重要的一部分,但这不是一个很好的选择。

首先我们定义我们的函数:

def removeItem( theList, theItem, typeOfItem=None ):

注意我已经给出了默认值None,因为第三个参数是可选的。

我们要做的第一件事就是测试typeOfItem。问题是它是一个索引然后会说"index"否则第二个参数会说"{item}"。所以它将是一个或另一个。 (如果不是这种情况该怎么办是一个你应该问的问题)。

索引部分很简单:

    if typeOfItem == "index":
        del(theList[theItem])

但现在它有点复杂,因为{ },我们必须删除它:

    else:
        theList.remove(theItem[1:-1])

最后一部分是删除一个 slice ,它从字符1(第二个字符)开始,到最后一个字符-1结束,从而删除{ }

所以带有测试的最终功能代码是:

def removeItem( theList, theItem, typeOfItem=None ):
    if typeOfItem == "index":
        del(theList[theItem])
    else:
        theList.remove(theItem[1:-1])

mylist = ["one" , "two" ,"three" , "four" , "five"]
removeItem(mylist, 3, "index")
print mylist

mylist = ["one" , "two" ,"three" , "four" , "five"]
removeItem(mylist, "{two}")
print mylist

注意函数和列表的一个重要特性。如果你改变了函数里面的列表,那么它也会改变它函数之外 - 它是同一个列表。数字和字符串不是这种情况。

相关问题