无法让我的 for 循环产生所需的结果

Can't get my for loop to produce desired result

还尝试了枚举和列表理解。但我只会专注于一件事并注释掉我尝试过的其他方法。我想也许我应该做一些涉及字典的事情??但我不知道该怎么做。它甚至不会让我定义一个空字典。所以我决定的策略是尝试编写一个程序,如果用户选择一个名称,并且在列表中找到该名称,索引中的项目将在右边(应该是适当的 phone 数字) 将被退回。我的 for 循环在底部。

A contact list is a place where you can store a specific contact with other associated information such as a phone number, email address, birthday, etc. Write a program that first takes in word pairs that consist of a name and a phone number (both strings). That list is followed by a name, and your program should output the phone number associated with that name.

例如:如果输入是:

Joe 123-5432 Linda 983-4123 Frank 867-5309
Frank

输出是:

867-5309

 ''' Type your code here. '''
    
    userEntered = input()
    selectedName = input()
    
    
    makeDict = {}
    
    
    
    listLength = len(userEntered.split())
    
    #for key, value in enumerate(makeDict):
        #key = userEntered.split()[0:listLength:2]
        #value =  userEntered.split()[1:listLength:2]
        
        
    #findNumber = [str(x) for x in userEntered.split() if str(x) == selectedName]
    
    #for index, value in enumerate(userEntered.split()):
        #if selectedName == value:
            #print(value[index+1])
        
    
  i = 0
for x in userEntered.split():
    while i <= listLength:
        if x == selectedName:
            answer = x[i+1]
            print(answer)
            break
        i+=1

输入程序输入(可选)

Joe 123-5432 Linda 983-4123 Frank 867-5309
Linda

此处显示程序输出

(Your program produced no output)

编辑:解决方案现在适用于:

i = 0
for x in userEntered.split():
    if userEntered.split()[i] == selectedName:
        answer = userEntered.split()[i+1]
        print(answer)
        break
    i+=1

您可以使用 str.split() 拆分 users/numbers,然后 zip() 创建字典。例如:

userEntered = input().split()
selectedName = input()

dct = dict(zip(userEntered[::2], userEntered[1::2]))
print(dct[selectedName])

打印(例如):

Joe 123-5432 Linda 983-4123 Frank 867-5309
Linda
983-4123

让我向您解释一下您的程序中有什么问题。

一个问题是您的内部 while 循环。你在那里使用 i 但你没有在条件中使用 i ,所以它总是会在第一次迭代或最后一次迭代时停止。即使它可行,您也不会在循环之间重置 i,因此它在 while 之后保持不变,这可能不是您想要的。如果你完全删除 while 循环,它应该可以工作!

另一种方法是使用带组的正则表达式来查找名称和数字模式,您也可以根据找到的结果创建字典。假设您获得了之前提到的输入:

userEntered = input()
selectedName = input()

userEntered如下:

Joe 123-5432 Linda 983-4123 Frank 867-5309

然后你可以从 re 调用 findall 为:

import re

contacts = dict(re.findall(r"([a-zA-Z]+)\s(\d+-\d+)", userEntered))
contacts[selectedName]

打印 selectedName 的联系人,所以如果 selectedName 是“Linda”,它会打印:

983-4123