查找重复项及其索引

2024-05-15 23:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用并行数组编写一个程序。程序应要求用户输入姓名,然后检查姓名是否在现有数组中,如果姓名在数组中,则返回名字、姓氏、在数组中找到的索引以及电话号码。如果匹配的名称不止一个,那么它将同时返回两个名称及其索引。 这是我到目前为止所拥有的,但我似乎无法弄清楚如何获得第二个副本的索引

name = ["David", "Tony", "Josh", "Chloe", "David", "Olivia"]
lastName = ["Smith", "Jones", "Brown", "Miller", "Brown", "Williams"]
phone = ["111-123-1234","222-123-1234","333-123-1234","444-123-1234","555-123-1234","662-123-1234"]
for i in range(len(name)):
    sName = input("Enter a Name: ")
    if sName in name:
        index = firstName.index(sName)
        print(name[index],lastName[index],"is located at index",index)
        print("Phone number:", phone[index])
        print()
    else:
        print("The name:", sName, "does not exist in our records")
        print("Please try a different name.")
        print()

#The output should be something like: 
#David Smith is located at index 0 
#Phone number: 111-123-1234
#
#David Brown is located at index 4 
#Phone number:555-123-1234

Tags: namein程序numberindexisphone数组
3条回答

这里有一个非常简单的解决方案

name = ["David", "Tony", "Josh", "Chloe", "David", "Olivia"]
lastName = ["Smith", "Jones", "Brown", "Miller", "Brown", "Williams"]
phone = ["111-123-1234","222-123-1234","333-123-1234","444-123-1234","555-123-1234","662-123-1234"]


found = False
sName = input("Enter a Name: ")

for i in range(len(name)):
    if sName == name[i]:
        print(name[i],lastName[i],"is located at index",i)
        print("Phone number:", phone[i])
        found = True

if found == False:
    print("The name:", sName, "does not exist in our records")
    print("Please try a different name.")

您不需要使用index函数,因为在使用for循环迭代列表时,如果发现目标名称是名称[i],那么i的值就是目标名称的索引。另外我搬家了

sName = input("Enter a Name: ")

在for循环之外。如果它仍在for循环中,则它仅将目标名称与当前索引i处的名称进行比较

以下是一个可能会影响作业的函数:

name = ["David", "Tony", "Josh", "Chloe", "David", "Olivia"]
lastName = ["Smith", "Jones", "Brown", "Miller", "Brown", "Williams"]
phone = ["111-123-1234","222-123-1234","333-123-1234","444-123-1234","555-123-1234","662-123-1234"]

def findIndex(find_name, first_name):
    pos = []
    for x in range(len(first_name)):
        if find_name == first_name[x]:
            pos.append(x)
    
    return pos


for i in range(len(name)):
    sName = input("Enter a Name: ")
    pos = findIndex(sName, name)
    if len(pos) > 0:
        for x in pos:
            print(name[x],lastName[x],"is located at index",x)
            print("Phone number:", phone[x])
            print()
            
    else:
        print("The name:", sName, "does not exist in our records")
        print("Please try a different name.")
        print()

下面是一个更具python风格的函数:

def findIndex(find_name, first_name):

    return [x for x in range(len(first_name)) if find_name == first_name[x]]

在Python listindex方法中,可以指定其他参数:

start:从哪个索引开始搜索

end:应该搜索到哪个索引项

找到第一个索引后,可以通过在第一个出现索引之后设置start索引来再次尝试搜索

参考:https://docs.python.org/3/tutorial/datastructures.html

相关问题 更多 >