繁体   English   中英

关于Python函数和列表的困惑

[英]Confusion about Python Functions and Lists

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

如果用户希望使用索引从列表中删除一个项目,则传递的第三个参数将是“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

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

您确实需要提高您的问题处理能力。 很难理解您要完成的任务。 在做出大约六个假设之后,我认为这是您正在尝试做的事情:

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

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

很明显,尽管您在python的基本知识上有一些空白。 您需要研究什么是功能,为什么有用以及如何使用它们。

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

谷歌一下! (查询=“定义函数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']

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

本练习的目的(大概)是练习编写函数。 是的,您可以在没有函数的情况下执行此操作,但是现在您需要练习编写函数并传递参数。 函数是编程中非常重要的部分,但这并不是一个适合的地方。

首先,我们定义函数:

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

注意,由于第三个参数是可选的,因此我给了默认值None

我们要做的第一件事是测试typeOfItem 问题是说它是一个索引,然后它将说"index"否则第二个参数将说"{item}" 因此将是其中一个。 (如果不是这种情况,应该问一个问题)。

索引部分很容易:

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

但是现在由于{ }而变得更加复杂,我们必须删除它:

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

最后一部分是删除切片 ,该切片从字符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

注意该功能和列表的重要功能。 如果您更改函数内部的列表,那么它也会同时更改函数外部的列表-它是相同的列表。 数字和字符串不是这种情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM