繁体   English   中英

使用Python编辑条目列表

[英]Edit list of entries using Python

到目前为止,我的脚本是:

#DogReg v1.0
import time
Students = ['Mary', 'Matthew', 'Mark', 'Lianne' 'Spencer'
            'John', 'Logan', 'Sam', 'Judy', 'Jc', 'Aj'  ]

print("1. Add Student")
print("2. Delete Student")
print("3. Edit Student")                             
print("4. Show All Students")
useMenu = input("What shall you do? ")
if(useMenu != "1" and useMenu != "2" and useMenu != "3" and useMenu != "4"):
    print("Invalid request please choose 1, 2, 3, or 4.")
elif(useMenu == "1"):
    newName = input("What is the students name? ")
    Students.append(newName)
    time.sleep(1)
    print(str(newName) + " added.")
    time.sleep(1)
    print(Students)
elif(useMenu == "2"):
    remStudent = input("What student would you like to remove? ")
    Students.remove(remStudent)
    time.sleep(1)
    print(str(remStudent) + " has been removed.")
    time.sleep(1)
    print(Students)
elif(useMenu == "3"):

因此,我试图让用户输入他们想要编辑和更改的名称。

我尝试查找用于编辑列表条目的功能,但没有找到我要查找的功能。

假设用户想要将'Mary'更改为'Maria'

student_old = 'Mary'
student_new = 'Maria'
change_index = Students.index(student_old)
Students[change_index] = student_new

请注意,您将必须添加适当的错误处理-例如,如果用户要求修改不在列表中的'Xavier' ,则会收到ValueError

这个怎么样?

elif(useMenu == "3"):

    oldName = input("What student would you like to edit? ")

    if oldName in Students:

        index = Students.index(oldName)
        newName = input("What is the student's new name? ")
        Students[index] = newName
        time.sleep(1)
        print(str(oldName) + " has been edited to " + str(newName))
        time.sleep(1)

    else: 

       print('Student' + oldName + 'not found!')

    print(Students)

输出:

1. Add Student
2. Delete Student
3. Edit Student
4. Show All Students
What shall you do? '3'
What student would you like to edit? 'Mary'
What is the student's new name? 'Marry'
Mary has been edited to Marry
['Marry', 'Matthew', 'Mark', 'LianneSpencerJohn', 'Logan', 'Sam', 'Judy', 'Jc', 'Aj']

暂无
暂无

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

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