微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python中的列表数据结构的应用

如何解决python中的列表数据结构的应用

祝您生活愉快愉快。 我现在正在研究python中的高级数据结构,并且试图通过此练习来查找有关处理列表问题的答案。请帮我解决这个错误。以下是问题:

” 创建一个程序,使用户可以(1)将产品添加到列表中,(2)删除项目,并(3)打印列表并退出

如果用户向列表中添加了一些内容,程序将询问“将添加什么?:”,并将其保存为列表中的最后一项。如果用户决定删除某项,则程序会通知用户列表中有多少项(列表中有[number]个项。“),并提示用户输入删除的项(”删除了哪个项? :“”。如果用户选择0,则第一个项目将被删除。当用户退出时,将为用户打印最终列表“以下项目保留在列表中:”,然后每行显示一个剩余项目。用户选择选项之外的任何内容包括删除项目时),程序都会响应“选择不正确。”当程序正常工作时,它会打印出以下内容

Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Apples
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Beer
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Carrots
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 2
There are 3 items in the list.
Which item is deleted?: 3
Incorrect selection.
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 2
There are 3 items in the list.
Which item is deleted?: 2
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 2
There are 2 items in the list.
Which item is deleted?: 0
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 4
Incorrect selection.
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 3
The following items remain in the list:
Beer

我的实现

mylist=[]
while True:
    n=int(input("Would you like to\n(1)Add or\n(2)Remove items or\n(3)Quit?: "))
    if n==1:
        a=input("What will be added?: ") 
        mylist.append(a)
    if n==2:
        count=len(mylist)
        print("There are ",count," items in the list.")
        b=int(input("Which item is deleted?: "))
        for b in range(len(mylist)):
            mylist.pop(b)
        else:
            print("Incorrect selection.")
    if n==3:
        print("The following items remain in the list:\n",mylist)
        break

程序会打印出来,如下所示:

Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Apples
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Beer
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Carrots
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 2
There are  3  items in the list.
Which item is deleted?: 3
Traceback (most recent call last):
  File "ohjelma.py",line 12,in <module>
    mylist.pop(b)
IndexError: pop index out of range

我不知道我遇到了atm错误。请在这件事上给予我帮助!!! 感谢您的时间和精力!

解决方法

列表中的索引从0开始。因此,在您的示例中,胡萝卜位于索引2。索引3不存在,因此无法从列表中弹出。 for循环似乎不起作用,您只需要检查输入是否小于列表的长度即可。您对n == 2的逻辑应该是这样的:

if n==2:
    count=len(mylist)
    print("There are ",count," items in the list.")
    b=int(input("Which item is deleted?: "))
    if b < count:
        mylist.pop(b)
    else:
        print("Incorrect selection.")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。