如何优化Python中列表搜索中冲突的多个条件?

我正在用 python 制作一个电话簿搜索程序,该程序在文本文件中搜索学校名称输入。在该程序中,系统会要求用户提供姓氏或名字和姓氏。然后,程序将搜索文本文件并打印与输入的电话号码相匹配的姓名。

因此,如果用户输入 Adams,结果将是:
John Adams,508-555-5555
Quicy Adams,508-555-5556

如果用户输入 John Adams,则只会打印他的名字。
John Adams,508-555-5555

我的问题是,我的 for 循环条件逐行读取列表。无论是否使用全名,它将打印与姓氏匹配的所有名称。
这是我的代码:

while True:

    original_name = input("Enter a last name, or first and last name: ")  # prompt user for name


    if original_name == "":   # create condition for infinite loop to end

        break


    l_name = original_name.lower()  # lower case to assist in finding a match

    s_name = l_name.split()         # split to allow a full name to become two variables


    if len(s_name) == 1:        # Set condition for last name if it is by itself to be properly placed in variable

        last_name = s_name[0]

    elif len(s_name) == 2:      # Set condition for first name and last name to go into proper variables

        first_name = s_name[0]

        last_name = s_name[1]

    else:

        print("Error: Input needs to be no more than 2 names!")  # error for when more than 2 names are given


    f = open("phones.txt", 'r')     # open text file being used

    numbers = f.readlines()         # read text file line by line


    for line in numbers:

        line = line.lower()     # lower case to assist in finding a match

        line = line.strip()     # strip to get rid of new lines

        line = line.split()     # split to allow for both first and last name to match



我知道我的问题在于条件。如果我先使用 elif 条件,即使使用全名,它也会打印具有相同姓氏的名称。

我查看了 stackflow 上的几个问题,看看我是否能弄清楚,但没有一个完全符合我的问题。另外,我想知道如何让逗号更接近姓氏,因为我的输出让它在姓氏前面浮动一个空格: John Adams , 508-555-5555。

我感谢您提供的所有帮助,并期待您传授的知识!


HUH函数
浏览 120回答 2
2回答

冉冉说

你想要一些类似的东西:if (len(s_name) == 2 and first_name == line[0] and last_name == line[1]) or (len(s_name) == 1 and last_name == line[1]):    print(line[0].capitalize(), line[1].capitalize(), ",", line[2])如果提供了两个名称并且 2 个匹配,或者如果提供了 1 个名称并且它与姓氏匹配,这将打印该行。值得注意的是,对于 lsit 行中的每个元素,您可能想要进行剥离,以避免由于空格而导致元素无法计算。

犯罪嫌疑人X

为什么要这么费力去了解姓氏和名字呢?尝试这个:while True:    if input("name").lower() in line.lower():        print(line)编辑def search(name):    with open('phones.txt','r') as file:        temp=[]        for i in file :            if name in i :                temp.append(i.split())        for i in temp:            i[0]=i[0]+' '+i[1]            i[1]=', '            print(''.join(i))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python