【问题标题】:How to optimize the multiple conditions in a list search that are conflicting in python?如何优化列表搜索中python中冲突的多个条件?
【发布时间】:2020-09-25 13:08:35
【问题描述】:

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

因此,如果用户输入 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

        if line[1] == last_name in line:    # This condition is to ensure a line is printed if only a last name is used
            print(line[0].capitalize(), line[1].capitalize(), ",", line[2])
        elif line[1] == last_name and line[0] == first_name in line: # when a first and last name is used
            print(line[0].capitalize(), line[1].capitalize(), ",", line[2])
        else:       
            continue

我知道我的问题在于条件句。如果我先使用 elif 条件,即使使用全名,它也会打印具有相同姓氏的名称。
我查看了有关 stackflow 的几个问题,看看我是否能弄清楚,但没有一个完全符合我的问题。另外,我想知道如何让逗号更接近姓氏,因为我的输出让它在姓氏前面浮动一个空格:John Adams,508-555-5555。
感谢您提供的所有帮助,并期待您传授的知识!

【问题讨论】:

  • 您是否尝试过一次读取列表,然后将其转换为可以在内存中使用的 python 对象(如字典或其他东西)?
  • 其中一些测试没有多大意义。例如,line[1] == last_name in line。这等价于line[1] == last_name and last_name in line,而后者又等价于line[1] == last_name。它在line 中的附加测试毫无意义,因为您已经知道它是否满足第一个条件。
  • @TomKarzes 啊,我不知道该声明中的逻辑。我会在以后的条件句中记住这一点。

标签: python list search conditional-statements


【解决方案1】:

你想要一些类似的东西:

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 行中的每个元素,您可能想要进行剥离,以避免由于空格而导致元素流鼻涕。

【讨论】:

  • 谢谢卡洛斯!我实施了您的条件,并且效果很好。我仍然对打印中的逗号有疑问,但这不是世界末日。再次感谢您!
【解决方案2】:

何必费尽心思去获取姓氏名字呢?试试这个:

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

【讨论】:

  • 我看到的问题是它不能满足我被要求的格式要求。由于文本文件的姓氏后面没有逗号,所以我必须将其添加到程序中。
  • 所以数据是:abc def xxxxxxxxx??
  • 是的。所以:约翰亚当斯 508-555-5555
  • 检查这个新的编辑。如果这是答案,请记住接受它作为解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 2020-12-14
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2013-11-18
  • 2012-10-24
相关资源
最近更新 更多