对Python列表数据库排序

对Python列表数据库排序,python,database,list,sorting,csv,Python,Database,List,Sorting,Csv,下一个代码被修改为包含一个新的菜单项“(r)”,以对保存在csv文件中的电话列表中的姓名/号码重新排序。这些步骤包括: 在主循环中添加两行,在菜单选项中添加一行,以打印出新的菜单选项(并将“r”添加到可接受的选项列表中),以及 执行重新排序的新函数。此函数被称为reorder\u phones() 用于运行此代码的文件与下面的文件类似 主要问题是我不知道如何保存和使用排序列表;如果有人能指导我,我将不胜感激 import os import csv phones = [] name_pos

下一个代码被修改为包含一个新的菜单项“(r)”,以对保存在csv文件中的电话列表中的姓名/号码重新排序。这些步骤包括:

  • 在主循环中添加两行,在菜单选项中添加一行,以打印出新的菜单选项(并将“r”添加到可接受的选项列表中),以及
  • 执行重新排序的新函数。此函数被称为
    reorder\u phones()
  • 用于运行此代码的文件与下面的文件类似

    主要问题是我不知道如何保存和使用排序列表;如果有人能指导我,我将不胜感激

    import os
    import csv
    
    
    phones = []
    name_pos = 0
    phone_pos = 1
    phone_header = [ 'Name', 'Phone Number']
    
    def proper_menu_choice(which):
        if not which.isdigit():
            print ("'" + which + "' needs to be the number of a phone!")
            return False
        which = int(which)
        if which < 1 or which > len(phones):
            print ("'" + str(which) + "' needs to be the number of a phone!")
            return False
        return True
    
    def delete_phone(which):
        if not proper_menu_choice(which):
            return
        which = int(which)
    
        del phones[which-1]
        print( "Deleted phone #", which)
    
    def edit_phone(which):
        if not proper_menu_choice(which):
            return
        which = int(which)
    
        phone = phones[which-1]
        print("Enter the data for a new phone. Press <enter> to leave unchanged.")
    
        print(phone[name_pos])
        newname = input("Enter phone name to change or press return: ")
        if newname == "":
            newname = phone[name_pos]
    
        print(phone[phone_pos])    
        newphone_num = input("Enter new phone number to change or press return: ")
        if newphone_num == "":
            newphone_num = phone[phone_pos]
    
        phone = [newname, newphone_num]
        phones[which-1] = phone
    
    
    def save_phone_list():
    
        f = open("myphones.csv", 'w', newline='')
        for item in phones:
            csv.writer(f).writerow(item)
        f.close()
    
    def load_phone_list():
        if os.access("myphones.csv",os.F_OK):
            f = open("myphones.csv")
            for row in csv.reader(f):
                phones.append(row)
            f.close()
    
    def show_phones():
        show_phone(phone_header, "")
        index = 1
        for phone in phones:
            show_phone(phone, index)
            index = index + 1
        print()
    
    def show_phone(phone, index):
        outputstr = "{0:>3}  {1:<20}  {2:>16}"
        print(outputstr.format(index, phone[name_pos], phone[phone_pos]))
    
    def create_phone():
        print("Enter the data for a new phone:")
        newname = input("Enter name: ")
        newphone_num = input("Enter phone number: ")
        phone = [newname,newphone_num]
        phones.append(phone)
    
    def reorder_phones():
        global phones       # this insures that we use the one at the top
        sorted(phones, key=lambda x: x[0])
    
    def menu_choice():
        """ Find out what the user wants to do next. """
        print("Choose one of the following options?")
        print("   s) Show")
        print("   n) New")
        print("   d) Delete")
        print("   e) Edit")
        print("   q) Quit")
        print("   r) Reorder")
        choice = input("Choice: ")    
        if choice.lower() in ['n','d', 's','e', 'q', 'r']:
            return choice.lower()
        else:
            print(choice +"?")
            print("Invalid option")
            return None
    
    
    def main_loop():
    
        load_phone_list()
    
        while True:
            choice = menu_choice()
            if choice == None:
                continue
            if choice == 'q':
                print( "Exiting...")
                break     # jump out of while loop
            elif choice == 'n':
                create_phone()
            elif choice == 'd':
                which = input("Which item do you want to delete? ")
                print("which is ", which)
                delete_phone(which)
            elif choice == 's':
                show_phones()
            elif choice == 'e':
                which = input("Which item do you want to edit? ")
                print("which is ", which)
                edit_phone(which)
            elif choice == 'r':
                reorder_phones()
            else:
                print("Invalid choice.")
    
        save_phone_list()
    
    
    # The following makes this program start running at main_loop() 
    # when executed as a stand-alone program.    
    if __name__ == '__main__':
        main_loop()
    
    导入操作系统
    导入csv
    电话=[]
    name_pos=0
    电话号码_pos=1
    电话头=['姓名','电话号码']
    定义正确的菜单选项(其中):
    如果没有,请选择哪个.isdigit():
    打印(““+”哪个+“”需要是电话号码!”)
    返回错误
    which=int(which)
    如果哪个<1或哪个>len(电话):
    打印(“'”+str(which)+“'需要是电话号码!”)
    返回错误
    返回真值
    def delete_电话(其中):
    如果菜单选择不正确(哪一项):
    返回
    which=int(which)
    戴尔手机[which-1]
    打印(“已删除的电话”,其中)
    def edit_电话(其中):
    如果菜单选择不正确(哪一项):
    返回
    which=int(which)
    电话=电话[which-1]
    打印(“输入新手机的数据。按可保持不变。”)
    打印(电话[姓名/位置])
    newname=input(“输入要更改的电话名或按return:”)
    如果newname==“”:
    newname=电话[姓名\位置]
    打印(电话[电话位置])
    newphone_num=input(“输入要更改的新电话号码或按return:”)
    如果newphone_num==“”:
    newphone\u num=电话[phone\u pos]
    phone=[newname,newphone\u num]
    电话[which-1]=电话
    def save_phone_list():
    f=打开(“myphones.csv”,“w”,换行符=”)
    对于手机中的项目:
    csv.writer(f).writerow(项目)
    f、 关闭()
    def load_phone_list():
    如果os.access(“myphones.csv”,os.F_OK):
    f=打开(“myphones.csv”)
    对于csv.reader(f)中的行:
    电话。追加(第行)
    f、 关闭()
    def show_phones():
    显示电话(电话标题“”)
    索引=1
    对于电话接入电话:
    显示电话(电话,索引)
    索引=索引+1
    打印()
    def显示_电话(电话,索引):
    outputstr=“{0:>3}{1:16}”
    打印(outputstr.格式(索引、电话[姓名],电话[电话号码])
    def create_phone():
    打印(“输入新手机的数据:”)
    newname=输入(“输入名称:”)
    newphone_num=输入(“输入电话号码:”)
    phone=[newname,newphone\u num]
    电话。附加(电话)
    def reorder_电话():
    全球手机#这确保了我们使用的是顶级手机
    已排序(电话,键=lambda x:x[0])
    def菜单_选项():
    “”“找出用户下一步想做什么。”“”
    打印(“选择以下选项之一?”)
    印刷品(s)展览)
    打印(“n)新的”)
    打印(“d)删除”)
    打印(“e)编辑”)
    打印(“q)退出”)
    打印(“r)重新排序”)
    选择=输入(“选择:”)
    如果[n'、'd'、's'、'e'、'q'、'r']中的choice.lower()为:
    返回选项。下()
    其他:
    打印(选项+“?”)
    打印(“无效选项”)
    一无所获
    def主回路()
    加载电话列表()
    尽管如此:
    选项=菜单\选项()
    如果选项==无:
    持续
    如果选项=='q':
    打印(“正在退出…”)
    中断#跳出while循环
    elif choice==“n”:
    创建电话()
    elif choice=='d':
    which=输入(“要删除哪个项目?”)
    打印(“which is”,which)
    删除_电话(哪个)
    elif choice==“s”:
    show_phones()
    elif choice==“e”:
    which=输入(“您要编辑哪个项目?”)
    打印(“which is”,which)
    编辑手机(哪个)
    elif choice==“r”:
    重新订购电话()
    其他:
    打印(“无效选择”)
    保存电话列表()
    #以下命令使该程序开始在main_loop()上运行
    #当作为独立程序执行时。
    如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
    主循环()
    
    这行代码的作用是什么-
    保存电话列表()
    ?您应该修剪代码中不需要询问的部分。请阅读说明:我包括了所有的代码,以防代码的另一部分需要更改!但本质上需要注意的一行是:def reorder_phones():global phones#这确保我们使用排序最靠前的一个(phones,key=lambda x:x[0])
    sorted
    返回一个新的列表,您没有捕获该列表,该函数存在并返回
    None
    。您可以
    返回已排序的(…
    或使用
    我的列表。排序()
    顺便说一句,您不需要使用
    全局
    。此行的作用是什么-
    保存电话列表()
    ??您应该修剪代码中不需要询问的部分。请阅读说明:我包含了所有代码,以防代码的另一部分需要更改!但本质上需要注意的一行是:def reorder_phones():global phones#这确保了我们使用的是位于顶部的代码(phones,key=lambda x:x[0])
    sorted
    返回一个新列表,您没有捕获该列表,并且该函数存在并返回
    None
    。您可以
    返回排序(…
    或使用
    my_list.sort()对列表进行排序。
    顺便说一句,您不需要使用
    全局
    import os
    import csv
    
    
    phones = []
    name_pos = 0
    phone_pos = 1
    phone_header = [ 'Name', 'Phone Number']
    
    def proper_menu_choice(which):
        if not which.isdigit():
            print ("'" + which + "' needs to be the number of a phone!")
            return False
        which = int(which)
        if which < 1 or which > len(phones):
            print ("'" + str(which) + "' needs to be the number of a phone!")
            return False
        return True
    
    def delete_phone(which):
        if not proper_menu_choice(which):
            return
        which = int(which)
    
        del phones[which-1]
        print( "Deleted phone #", which)
    
    def edit_phone(which):
        if not proper_menu_choice(which):
            return
        which = int(which)
    
        phone = phones[which-1]
        print("Enter the data for a new phone. Press <enter> to leave unchanged.")
    
        print(phone[name_pos])
        newname = input("Enter phone name to change or press return: ")
        if newname == "":
            newname = phone[name_pos]
    
        print(phone[phone_pos])    
        newphone_num = input("Enter new phone number to change or press return: ")
        if newphone_num == "":
            newphone_num = phone[phone_pos]
    
        phone = [newname, newphone_num]
        phones[which-1] = phone
    
    
    def save_phone_list():
    
        f = open("myphones.csv", 'w', newline='')
        for item in phones:
            csv.writer(f).writerow(item)
        f.close()
    
    def load_phone_list():
        if os.access("myphones.csv",os.F_OK):
            f = open("myphones.csv")
            for row in csv.reader(f):
                phones.append(row)
            f.close()
    
    def show_phones():
        show_phone(phone_header, "")
        index = 1
        for phone in phones:
            show_phone(phone, index)
            index = index + 1
        print()
    
    def show_phone(phone, index):
        outputstr = "{0:>3}  {1:<20}  {2:>16}"
        print(outputstr.format(index, phone[name_pos], phone[phone_pos]))
    
    def create_phone():
        print("Enter the data for a new phone:")
        newname = input("Enter name: ")
        newphone_num = input("Enter phone number: ")
        phone = [newname,newphone_num]
        phones.append(phone)
    
    def reorder_phones():
        global phones       # this insures that we use the one at the top
        sorted(phones, key=lambda x: x[0])
    
    def menu_choice():
        """ Find out what the user wants to do next. """
        print("Choose one of the following options?")
        print("   s) Show")
        print("   n) New")
        print("   d) Delete")
        print("   e) Edit")
        print("   q) Quit")
        print("   r) Reorder")
        choice = input("Choice: ")    
        if choice.lower() in ['n','d', 's','e', 'q', 'r']:
            return choice.lower()
        else:
            print(choice +"?")
            print("Invalid option")
            return None
    
    
    def main_loop():
    
        load_phone_list()
    
        while True:
            choice = menu_choice()
            if choice == None:
                continue
            if choice == 'q':
                print( "Exiting...")
                break     # jump out of while loop
            elif choice == 'n':
                create_phone()
            elif choice == 'd':
                which = input("Which item do you want to delete? ")
                print("which is ", which)
                delete_phone(which)
            elif choice == 's':
                show_phones()
            elif choice == 'e':
                which = input("Which item do you want to edit? ")
                print("which is ", which)
                edit_phone(which)
            elif choice == 'r':
                reorder_phones()
            else:
                print("Invalid choice.")
    
        save_phone_list()
    
    
    # The following makes this program start running at main_loop() 
    # when executed as a stand-alone program.    
    if __name__ == '__main__':
        main_loop()