这是一个家庭作业问题,我掌握了基础知识,但我似乎找不到搜索两个并行数组的正确方法。
原始问题:设计一个程序,它有两个并行数组:一个String
名为people
name 的数组用七个人的名字初始化,一个名为 name 的String
数组phoneNumbers
用你朋友的电话号码初始化。该程序应允许用户输入人名(或人名的一部分)。people
然后它应该在数组中搜索那个人。如果找到这个人,它应该从phoneNumbers
数组中获取那个人的电话号码并显示它。如果未找到此人,程序应显示一条消息指示。
我当前的代码:
# create main
def main():
# take in name or part of persons name
person = raw_input("Who are you looking for? \n> ")
# convert string to all lowercase for easier searching
person = person.lower()
# run people search with the "person" as the parameters
peopleSearch(person)
# create module to search the people list
def peopleSearch(person):
# create list with the names of the people
people = ["john",
"tom",
"buddy",
"bob",
"sam",
"timmy",
"ames"]
# create list with the phone numbers, indexes are corresponding with the names
# people[0] is phoneNumbers[0] etc.
phoneNumbers = ["5503942",
"9543029",
"5438439",
"5403922",
"8764532",
"8659392",
"9203940"]
现在,我的整个问题从这里开始。如何对姓名进行搜索(或部分搜索),并返回人员数组中人员姓名的索引并相应地打印电话号码?
更新:我将此添加到代码底部以进行搜索。
lookup = dict(zip(people, phoneNumbers))
if person in lookup:
print "Name: ", person ," \nPhone:", lookup[person]
但这仅适用于完全匹配,我尝试使用它来获得部分匹配。
[x for x in enumerate(people) if person in x[1]]
但是'tim'
,例如,当我搜索它时,它会返回[(5, 'timmy')]
. 如何获取该索引5
并将其应用到print phoneNumbers[
从搜索返回的索引中]
?
更新 2:终于让它完美地工作了。使用此代码:
# conduct a search for the person in the people list
search = [x for x in enumerate(people) if person in x[1]]
# for each person that matches the "search", print the name and phone
for index, person in search:
# print name and phone of each person that matches search
print "Name: ", person , "\nPhone: ", phoneNumbers[index]
# if there is nothing that matches the search
if not search:
# display message saying no matches
print "No matches."