【问题标题】:Sort a Python list database对 Python 列表数据库进行排序
【发布时间】:2017-04-19 01:17:21
【问题描述】:

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

  1. 在 main_loop 中添加两行,在 menu_choice 中添加一行以打印出新的菜单选项(并将“r”添加到可接受的选项列表中),以及
  2. 用于重新排序的新功能。这个函数被称为reorder_phones()

用于运行此代码的文件类似于下面的文件。

Before:
Choice: s
     Name                     Phone Number 
     1  Jerry Lopez             (212) 842-2527
     2  George Sierr            (212) 452-8145
     3  Elaine Benea            (212) 452-8723
After:
Choice: s
     Name                     Phone Number 
     1  Elaine Benea            (212) 452-8723
     2  George Sierr            (212) 452-8145
     3  Jerry Lopez             (212) 842-2527

主要问题是我不确定如何保存和使用排序列表;如果有人可以指导我,我将不胜感激。

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()

【问题讨论】:

  • 这条线是做什么的 - save_phone_list() ??
  • 你应该修剪你没有询问的代码部分。请阅读说明:stackoverflow.com/help/mcve
  • 我包含了所有代码,以防其他部分代码需要更改!但本质上需要注意的行是: def reorder_phones(): globalphones # 这确保我们使用顶部排序的(phones, key=lambda x: x[0])
  • sorted 返回一个您未捕获的新列表,并且该函数存在并返回 None。您可以return sorted(... 或使用my_list.sort() 对列表进行就地排序
  • 顺便说一句,您不需要使用global

标签: python database list sorting csv


【解决方案1】:

使用下面的方法进行排序,sort()函数对原始文件进行排序,sorted()对结果进行排序。

def reorder_phones():
    global phones       # this insures that we use the one at the top
    phones.sort()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多