You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python通讯录CSV程序中按姓名升序排序并展示?

问题解决:CSV通讯录按姓名升序排序展示

我用Python实现了基于CSV的通讯录管理程序,包含创建、添加、展示、按号查名、按名查号功能,但无法实现按姓名升序排序展示全部数据,使用sort和sorted方法时出现报错。

问题原因

csv.reader()返回的是迭代器对象,而非可修改的列表,因此无法直接调用sort()方法;即便用sorted(),也需要先将迭代器转换为列表,否则迭代器遍历一次后就会为空,无法完成排序操作。

解决方案

修改展示函数,先把CSV中的数据读取为列表,再按姓名(每个联系人条目的第一个元素)排序,之后遍历展示。也可以新增排序展示的独立功能,不改动原有展示逻辑。

修改后的完整代码

import csv
sure="y"
def create():
    s="y"
    f=open("tele.csv","w",newline="")
    print("="*184)
    print(" "*77,"Creating a telephone directory"," "*77)
    print("="*184)
    writer=csv.writer(f)
    while s=="y":
        a=input("Enter Name : ")
        b=input("Enter Contact Number : ")
        writer.writerow([a,b])
        print()
        s=input("Do you want to add another contact? (y/n) : ")
        print()
    print("Telephone Directory created successfully!")
    print("="*184)
    f.close()

def add():
    f=open("tele.csv","a",newline="")
    print("="*184)
    print(" "*82,"Add a New Contact"," "*82)
    print("="*184)
    writer=csv.writer(f)
    a=input("Enter Name : ")
    b=input("Enter Contact Number : ")
    writer.writerow([a,b])
    print()
    print("Contact added successfully!")
    print("="*184)
    f.close()


def disp():
    f=open("tele.csv","r")
    print("="*184)
    print(" "*83,"Telephone Directory"," "*83)
    print("="*184)
    print("%50s"%"Contact Name","%90s"%"Contact Number")
    print("="*184)
    reader=csv.reader(f)
    # 将迭代器转为列表
    contacts = list(reader)
    # 按姓名升序排序,key取每个元素的第一个值(姓名)
    contacts_sorted = sorted(contacts, key=lambda x: x[0])
    for i in contacts_sorted:
        print("%50s"%str(i[0]),"%90s"%str(i[1]))
    print(" "*184)
    f.close()

def num():
    f=open("tele.csv","r")
    num=input("Enter the contact number : ")
    reader=csv.reader(f)
    nam=""
    for i in reader:
        if num==i[1]:
            nam=str(i[0])
            break
    if len(nam)!=0:
        print(f"Contact Name corresponding to number {num} is {nam}.")
    else:
            print(f"Contact Name corresponding to number {num} is not found")
    print("="*184)

def nam():
    f=open("tele.csv","r")
    nam=input("Enter the contact name : ")
    num=""
    reader=csv.reader(f)
    for i in reader:
        if nam==i[0]:
            num=str(i[1])
            break
    if len(num)!=0:
        print(f"Contact Number corresponding to name {nam} is {num}.")
    else:
        print(f"Contact Number corresponding to name {nam} is not found")
    print("="*184)

print("="*184)
print(" "*83,"Telephone Directory Software"," "*83)
print("="*184)
print('''1) Create a Telephone Directory
2) Add a new contact
3) Display the Telephone Directory (sorted by name)
4) Search for contact name by number
5) Search for contact number by name
''')
while sure=="y":
    choice=int(input("Enter your choice : "))
    if choice==1:
        create()
    elif choice==2:
        add()
    elif choice==3:
        disp()
    elif choice==4:
        num()
    elif choice==5:
        nam()
    else:
        print("Invalid Choice!!!")
    br=input("Do you want to do further operations? (y/n) : ")
    print()
    if br==sure:
        continue
    else:
        break
print("Thanks for running the program!")

关键修改点

  1. 在disp()函数中,将csv.reader转换为列表:contacts = list(reader)
  2. 使用sorted()函数,通过key=lambda x: x[0]指定按姓名(每个列表元素的第一个值)升序排序
  3. 遍历排序后的列表展示数据
  4. 优化部分打印语句格式,用f-string提升可读性
  5. 更新菜单提示,明确展示功能已支持排序

额外扩展

如果希望保留原有未排序的展示功能,可以新增一个独立的排序展示函数:

def disp_sorted():
    f=open("tele.csv","r")
    print("="*184)
    print(" "*79,"Telephone Directory (Sorted by Name)"," "*79)
    print("="*184)
    print("%50s"%"Contact Name","%90s"%"Contact Number")
    print("="*184)
    reader=csv.reader(f)
    contacts = list(reader)
    contacts_sorted = sorted(contacts, key=lambda x: x[0])
    for i in contacts_sorted:
        print("%50s"%str(i[0]),"%90s"%str(i[1]))
    print(" "*184)
    f.close()

之后在菜单中添加6) Display Telephone Directory sorted by name,并在循环中处理choice==6的分支即可。

内容的提问来源于stack exchange,提问作者Aditya Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 14:21:00